Baban Faraj Baban Faraj - 2 months ago 15
Java Question

How can you create objects in a loop and save its memory to a different location?

how can I create numerous objects inside a loop and store each cycle inside a different location of memory?
For example, I am writing a test program for my shopping bag program, and I would like to add Candy and Milk to my shopping bag. When I type these objects in for the user input, and print it out, it only prints out the last object. Which is milk. I have thought about using array list, but I do not know how to add the object name,price,quantity to that array list of an object.

Here is my code if you would prefer to look at it:

import java.util.ArrayList;
import java.util.Scanner;


public class TestDriver
{

public static void main (String[]args)
{
ArrayList<ShoppingBag>list= new ArrayList<ShoppingBag>();
Scanner sc = new Scanner(System.in);
Boolean answer=true;

ShoppingBag shop= new ShoppingBag(6);

while(answer==true)
{
System.out.println("Enter the name of the items(Enter None to stop): ");
String name=sc.next();
if(name.equalsIgnoreCase("none"))
{
answer=false;
}
else
{
shop.setName(name);
System.out.println("Enter count: ");
int count=sc.nextInt();
shop.setNumberOfItems(count);
System.out.println("Enter cost(unit price): ");
float subTotal= sc.nextFloat();
shop.setSubtotal(subTotal);
}
}
System.out.println(shop.toString());
}
}

Answer

You are creating just one instance of an object of type ShoppingBag.

When you do

    ShoppingBag shop= new ShoppingBag(6);

this creates in memory a new object of type ShoppingBag, let's call this instance "shop".

When you enter inside the loop and you execute this:

            shop.setName(name);
            shop.setNumberOfItems(count);
            shop.setSubtotal(subTotal); 

this shop variable is referring to "shop", so it will overwrite existing fields.

In the first iteration you will have

shop.name = candy

In the second iteration you will have

shop.name = milk //this is still same shop object in the same memory location* with a new overwrite name!

To have two different object you will need to instantiate a new object each time, so the else branch will look like this:

        else
            {
            ShoppingBag shop= new ShoppingBag(6);
            shop.setName(name);
            System.out.println("Enter count: ");
            int count=sc.nextInt();
            shop.setNumberOfItems(count);
            System.out.println("Enter cost(unit price): ");
            float subTotal= sc.nextFloat();
            shop.setSubtotal(subTotal); 
            list.add(shop);
            }

Notice that the new ShoppingBag is created each time inside the loop. At this point you need to "keep the pointers" to the objects somewhere, and this is were list.add(shop) comes in to play.

If you want to print them after you can just do:

for (ShoppingBag shoppingBag : list){
   System.out.println(shoppingBag);
}