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.