How to copy java.util.list Collection

前端 未结 2 1809
半阙折子戏
半阙折子戏 2021-02-01 13:53

I am implementing a Java class responsible for ordering java.util.List. The problem comes when I use this class. I\'m able to ordering the list but I want to copy the \"original

2条回答
  •  名媛妹妹
    2021-02-01 14:06

    Use the ArrayList copy constructor, then sort that.

    List oldList;
    List newList = new ArrayList(oldList);
    Collections.sort(newList);
    

    After making the copy, any changes to newList do not affect oldList.

    Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

提交回复
热议问题