如何阻止对一个ArrayList中的对象进行修改,同时也不能修改另一个ArrayList中的同一对象[重复]

问题描述 投票:0回答:1
我有以下代码,该代码旨在通过与字符串进行比较从一个数组列表中找到一个对象,然后将该对象添加到另一个数组列表中,然后在第二个数组列表中修改该对象的参数,但是正在发生的是在两个数组列表中都修改了该对象的参数。

我是Java的新手,并且了解到因为Java通过引用传递,所以我正在修改内存中的位置,而不是它的副本,但是,因为我正在通过(特别是通过第二个arraylist,我认为它将仅修改那个arraylist中的对象。

我在这里错过了什么,如何克服这个问题?

getTheBasket()

。返回一个存储产品类型对象的数组列表,

theProductList

是一个存储产品类型对象的数组列表。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); } 在哪里找到:
public Product find(String nameInput){

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

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

我对这里的新手问题深表歉意,但我尝试了许多不同的设置,但似乎不起作用。

我有以下代码,该代码旨在通过与字符串进行比较从一个数组列表中找到一个对象,然后将该对象添加到另一个数组列表,然后在第二个数组列表中修改对象的参数...
java object arraylist pass-by-reference add
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.