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

标签 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)对象中的数据被更改,而不是currentBundle对象中的数据。我错过了什么?

最佳答案

当你这样做时,

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 ?

关于java - 变量的保存/分配/设置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50793514/

相关文章:

java - 如何在 java 8 中使用带有 null 和空检查的平面图合并多个列表?

vb.net - 如何在 Visual Basic 2010 中引用带有变量的控件?

variables - TFS CI 构建触发器包含变量

opengl - 在 Cg 中访问 OpenGL 状态变量

Java:检索列表中值的最佳方法

JPA将列表传递给命名 native 查询中的IN子句

java - 以下代码的复杂性

java - 在现在的C++和Java中,double类型和float类型: if (x == 0. 0)是正确的吗?

java - 将蓝牙 Android 客户端连接到蓝牙 Java 服务器

java - 将 ArrayList 转换为数组(有点不同)