错误的保存/分配/设置变量

时间:2018-06-11 08:36:25

标签: java variables arraylist local-variables

我的代码有问题,我没有发现错误,必须是微不足道的。

// This list is filled with Objects of Matcher
ArrayList<Matcher > fullListForBundle = new ArrayList<>();

// making a new ArrayList
ArrayList<Matcher> bundlelist = new ArrayList<>();

// making a new object
Matcher currentBundle = new Matcher();

// Searching trough an Arraylist of Objects.
for (Matcher current : stockDataCompleteWithBundle)
{
    // Get an Identifier
    String han = current.getThirdColumn();
    // Search through an other list to match identifier
    for (int i = 0; i < fullListForBundle.size(); i++)
    {
        // If identifier matches then do:
        if (fullListForBundle.get(i).getFifteenthColumn().equals(han))
        {
            // I want to get the right object and save it in currentBundle
            currentBundle = fullListForBundle.get(i);

            // !!! Here begins my problem !!!

            // Then I want to change two Strings in that particular Object
            currentBundle.setFirstColumn(current.getFirstColumn());
            currentBundle.setThirteenthColumn(current.getSecondColumn());

            // And add that object to a new Arraylist
            bundlelist.add(currentBundle);
            }

        }
    }

我的问题是:通过设置firstColumn和thirteenthColumn,fullListBundle.get(i)Object中的数据被更改,而不是currentBundle对象。我错过了什么?

2 个答案:

答案 0 :(得分:2)

当你这样做时,

currentBundle = fullListForBundle.get(i);

currentBundlefullListForBundle.get(i)都引用了堆中的同一个对象。你应该看到两者都有相同的结果。如果您只想让currentBundle进行更改,请尝试

 currentBundle = fullListForBundle.get(i).clone();

编辑:Object.clone()方法具有protected访问权限,这意味着它对同一个包中的子类和类是可见的。

最好有一个复制构造函数来手动复制对象。

/**
    Deep copy all the information from other to this
*/
public Matcher(Matcher other) {
   this.id = other.id;
}

Read Why a copy constructor by Josh Bloch ?

答案 1 :(得分:0)

这是因为您使用的是同一个对象。您需要获取克隆对象并进行更改。

currentBundle = fullListForBundle.get(i).clone()