0

I have the following code which is designed to find an object from one arraylist by comparing to a string, then add the object to another arraylist, then modify a parameter of the object in the second arraylist, however what is happening is that the parameter for that object is being modified in both arraylists.

I am new to java and learning that because java passes by reference I am modifying the location in the memory, not a copy of it, however because I am accessing the modification method (getQuantity()) specifically through the second arraylist, I thought that it would modify the object in that arraylist and that only.

What have I missed here and how can I overcome this issue?

getTheBasket(). returns an arraylist that stores objects of type product, and theProductList is an arraylist that stores objects of type product.

public void addToBasket(){

             String productName = jCustomerProductSelectionBox.getSelectedItem().toString();
             Integer quantity = Integer.valueOf(jCustomerQuanityTextField.getText());

                    castedCustomer.getTheBasket().add(theProductList.find(productName));
                    castedCustomer.getTheBasket().find(productName).setQuantity(quantity);

             }

where find is:

public Product find(String nameInput){

  Product selection = null;  
    for(Product product: this.Products){

        if(product.getName().equalsIgnoreCase(nameInput)){
        selection = product;
        break;
        }  
    }    
return selection;
}

My apologies for the novice question here but I have tried a number different set ups and non seem to work.

1 Answers1

0

The answer below is one of the answers from the question:

How do I copy an object in Java?

public class Deletable implements Cloneable{

    private String str;
    public Deletable(){
    }
    public void setStr(String str){
        this.str = str;
    }
    public void display(){
        System.out.println("The String is "+str);
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

and wherever you want to get another object, simple perform cloning. e.g:

Deletable del = new Deletable();
Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                 // object, the changes made to this object will
                                 // not be reflected to other object

I have not deleted my question because it serves the purpose of helping people with arraylist specific questions, the object can simply be taken out of the array list in any chosen way and then cloned with the method above.