【问题标题】:Changing added array changes the arraylist to which I added it too更改添加的数组也会更改我添加的数组列表
【发布时间】:2016-11-28 00:47:36
【问题描述】:

我正在尝试将数组列表添加到我相信的数组列表的数组列表中(对不起,我是一个初学者),但是每当我取消临时数据以便我可以获取要添加的下一行数据时,它会将主数组列表更改为好吧。有没有办法只复制值而不指向同一个引用?

for (int n=0; n!=cellCount+1; n++)
        {
            temp.add(inputFile.nextDouble());
            System.out.println(temp);
        }

        mainList.add(temp);


    //}
temp.clear();
System.out.println(mainList);

打印: [0.0, 4.0, 6.0, 9.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0, 15.0]作为清空前的最终临时数组列表

[[]]作为主列表

【问题讨论】:

标签: java arraylist


【解决方案1】:

我假设temp 是你的ArrayList

当你这样做时:

mainList.add(temp);

您将对该数组列表的引用放入mainList。它不是它的副本,它是对它的引用。你只是每次都重复使用相同的ArrayList

相反,在每个循环中创建一个 ArrayList(然后你就不需要clear),例如:

while (/*...whatever, there's clearly some loop here..*/) {
    temp = new ArrayList();
    for (int n=0; n!=cellCount+1; n++)
    {
        temp.add(inputFile.nextDouble());
        System.out.println(temp);
    }

    mainList.add(temp);
}
System.out.println(mainList);

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2021-02-25
    • 2021-11-20
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多