Java ArrayList copy

前端 未结 8 824
说谎
说谎 2020-11-22 15:19

I have an ArrayList l1 of size 10. I assign l1 to new list reference type l2. Will l1 and l2 po

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 15:58

    Just for completion: All the answers above are going for a shallow copy - keeping the reference of the original objects. I you want a deep copy, your (reference-) class in the list have to implement a clone / copy method, which provides a deep copy of a single object. Then you can use:

    newList.addAll(oldList.stream().map(s->s.clone()).collect(Collectors.toList()));
    

提交回复
热议问题