简体   繁体   English

两种将ArrayList添加到另一种方式的意外输出

[英]Unexpected outputs from two different ways of adding an ArrayList to another

In some program as following: 在以下某些程序中:

ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp=new ArrayList<Integer>();

I want to add temp into result, if I use 我想在结果中添加temp

result.add(new ArrayList<Integer>(temp));

then the final output is correct, but if I use 那么最终的输出是正确的,但是如果我使用

result.add(temp);

then my final output is wrong. 那么我的最终输出是错误的。 Why? 为什么? Thanks for the help! 谢谢您的帮助!

The question does not show what is actually wrong and what the desired output is supposed to be. 该问题并未显示出实际上是什么错误以及期望的输出应该是什么。

This, result.add(new ArrayList<Integer>(temp)) , and this, result.add(temp) will both produce the same contents in result 这个result.add(new ArrayList<Integer>(temp))和这个result.add(temp)都将在result产生相同的内容

Without understanding clearly the desired output, I cannot see what is actually wrong with the code. 如果没有清楚地了解所需的输出,我将看不到代码的实际错误。

Further, it is better practice to refer to the ArrayList as a List on the left side and use the <> diamond on the right. 此外,更好的做法是将ArrayList称为左侧的List并在右侧使用<>菱形。 Make your coding easier and clearer: 使您的编码更轻松,更清晰:

    List<List<Integer>> result = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();
    temp.add(1);
    temp.add(2);
    result.add(temp);
    System.out.println("Result: " + result);

The output is exactly as specified and is a List<List<Integer>> : 输出与指定的完全相同,并且为List<List<Integer>>

Result: [[1, 2]] 结果:[[1,2]]

When you call: 你打电话时:

result.add(new ArrayList<Integer>(temp));

temp is copied into a new ArrayList and the end-result will contain the "untouched" copy. temp被复制到新的ArrayList中,最终结果将包含“未修改”的副本。

By calling: 通过致电:

result.add(temp)


you're adding temp itself to the result so the actions you'll preform later-on on temp will be reflected in result (that's the unwanted behavior you described). 您将temp本身添加到result以便稍后在temp将反映在result (这是您描述的不需要的行为)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM