【问题标题】:How to stop the modification of an object in one ArrayList from also modifying the same object in another ArrayList [duplicate]如何停止修改一个ArrayList中的对象,同时修改另一个ArrayList中的同一对象[重复]
【发布时间】:2020-06-06 23:40:52
【问题描述】:

我有以下代码,旨在通过与字符串比较从一个数组列表中查找对象,然后将该对象添加到另一个数组列表,然后修改第二个数组列表中对象的参数,但是发生的事情是该对象的参数正在两个数组列表中进行修改。

我是 java 新手并了解到因为 java 通过引用传递我正在修改内存中的位置,而不是它的副本,但是因为我正在访问修改方法 (getQuantity() ) 特别是通过第二个数组列表,我认为它会修改该数组列表中的对象,并且仅此而已。

我在这里遗漏了什么,我该如何克服这个问题?

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 不是传递引用。 Java 总是按值传递。

标签: java object arraylist pass-by-reference add


【解决方案1】:

下面的答案是问题的答案之一:

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();
    }
}

无论您想在何处获取另一个对象,只需执行克隆即可。例如:

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

我没有删除我的问题,因为它的目的是帮助人们解决特定于数组列表的问题,可以简单地以任何选择的方式将对象从数组列表中取出,然后使用上述方法进行克隆。

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多