简体   繁体   中英

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? 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. So you are able to use list2 as if it were list1; however changes you make to 2 will be reflected in 1.

list2 = list1

This assignment simply assigns the reference list2 to point at the same List as list1 . (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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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