简体   繁体   English

从一个列表复制到另一个列表

[英]Copying from one list to another

I have a list of sets of pairs. 我有一组对的列表。 If I use equal does it copy every set over? 如果我使用相同的,它会复制每一套?

List<HashSet<Pair>> list1 = new ArrayList<HashSet<Pair>>();
List<HashSet<Pair>> list2 = new ArrayList<HashSet<Pair>>();

list1.add(0, new HashSet<Pair>());
list1.add(1, new HashSet<Pair>());
list1.add(2, new HashSet<Pair>());
list1.add(3, new HashSet<Pair>());

If I do list2 = list1 , does it copy over perfectly? 如果我做list2 = list1 ,它是否完美复制? Because when I use it, it crashes. 因为当我使用它时,它会崩溃。

Iterator<Pair> it1 = list2.get(0).iterator();
Iterator<Pair> it2 = list2.get(1).iterator();
Iterator<Pair> it3 = list2.get(2).iterator();
Iterator<Pair> it4 = list2.get(3).iterator();

No. The assignment doesn't copy anything, and instead updates the list2 reference to point to list1. 否。赋值不会复制任何内容,而是将list2引用更新为指向list1。 So you are able to use list2 as if it were list1; 所以你可以使用list2,就像它是list1一样; however changes you make to 2 will be reflected in 1. 但是你对2做的改变将反映在1中。

list2 = list1

This assignment simply assigns the reference list2 to point at the same List as list1 . 此赋值仅指定引用list2指向与list1相同的List。 (Note that there is only one list with two references to it.) If you want to copy the list, you need to use a copy constructor: (请注意,只有一个列表包含两个引用。)如果要复制列表,则需要使用复制构造函数:

list2 = new ArrayList<HashSet<Pair>>(list1);

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

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