【问题标题】:Wrong saving/allocation/setting of variables错误的保存/分配/设置变量
【发布时间】:2018-11-20 10:55:29
【问题描述】:

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

// 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) 对象中的数据发生了变化,而不是 currentBundle 对象。我错过了什么?

【问题讨论】:

    标签: java variables arraylist local-variables


    【解决方案1】:

    当你这样做时,

    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 ?

    【讨论】:

    • 如果Matcherjava.util.regex.Matcher,那么这个建议将不起作用,因为Matcher 没有实现Cloneable
    • @DodgyCodeException currentBundle 是一个 Matche 。而currentBundle 有一个名为setFirstColumn 的方法。所以不是java.util.regex.Matcher。并且非常类将 Object 作为超类。 Object 类有一个 clone 方法。所以java.util.regex.Matcher 也会有一个clone 方法。
    • @DodgyCodeException Matcher 是我自己的类,其名称与 Matcher 不同(我只是想将我的类名更改为通用名称)。 @prime 无论如何:currentBundle = fullListForBundle.get(i).clone(); 不起作用,因为“Object 类型的方法 clone() 不可见”
    • @akBen 那么您需要自己实现一个clone() 方法,或者,better still, write a copy constructor 然后执行currentBundle = new Matcher(fullListForBundle.get(i));
    • @DodgyCodeException 谢谢。我写了一个复制构造函数。为我工作。
    【解决方案2】:

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

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

    【讨论】:

    • 我尝试克隆我的列表,但引用不会被克隆,我得到的结果与以前相同。
    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多