我有两个包含相同对象的列表.如何更改一个列表而不更改另一个列表? [英] I have two lists containing the same objects. How do I change one list without changing the other?

查看:52
本文介绍了我有两个包含相同对象的列表.如何更改一个列表而不更改另一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我仅将对象放入listOfRates,然后通过复制创建inverseListOfRates时,我首先注意到了此问题.但是即使使用这种方法,我也不能更改一个列表而不更改另一个列表.

如何解决此问题?

  List< HistoricRate>listOfRates = new ArrayList< HistoricRate>();List< HistoricRate>inverseListOfRates = new ArrayList< HistoricRate>();的(HistoricRate费率:费率){listOfRates.add(rate);inverseListOfRates.add(rate);}inverseListOfRates.forEach(r-> r.setMid(1/r.getMid())); 

解决方案

两个列表引用的是同一对象.因此,如果您更改第一个,则第二个也将更改.

解决方案是在将对象添加到第二个列表之前克隆该对象(将其副本创建到新实例中).

要克隆对象,可以使用以下建议之一:

1-复制构造函数:

  classicRateRate {私有字符串字段;公共HistoricRate(HistoricRate另一个){this.field = another.field;//您可以访问}} 

2- HistoricRate必须实现Cloneable接口

实施方法克隆以复制对象.

3-使用org.apache.commons.lang.SerializationUtils如下:

(HistoricRate费率:费率){listOfRates.add(rate);inverseListOfRates.add(SerializationUtils.clone(rate));}

I first noticed this problem when I only put the objects in listOfRates and then created inverseListOfRates by copying it. But even using this method, I can't alter one list without altering the other.

How do I solve this issue?

List<HistoricRate> listOfRates = new ArrayList<HistoricRate>();
List<HistoricRate> inverseListOfRates = new ArrayList<HistoricRate>();

for (HistoricRate rate : rates){
    listOfRates.add(rate);
    inverseListOfRates.add(rate);
}

inverseListOfRates.forEach(r -> r.setMid(1 / r.getMid()));

解决方案

The two lists are referencing the same object. So if you change the first, the second will change also.

The solution is to clone the object (Creating a copy of it into a new instance) before adding it into the second list.

To clone the object you can either use one of the following suggestions:

1- A constructor by copy :

class HistoricRate {
  private String field;

  public HistoricRate (HistoricRate another) {
    this.field= another.field; // you can access  
  }
}

2- HistoricRate must implement Cloneable interface

Implement the method clone to copy the object.

3- Use org.apache.commons.lang.SerializationUtils as below :

for (HistoricRate rate : rates){
    listOfRates.add(rate);
    inverseListOfRates.add(SerializationUtils.clone(rate));
}

这篇关于我有两个包含相同对象的列表.如何更改一个列表而不更改另一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆