How to copy java.util.list Collection

前端 未结 2 1807
半阙折子戏
半阙折子戏 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:03

    You may create a new list with an input of a previous list like so:

    List one = new ArrayList()
    //... add data, sort, etc
    List two = new ArrayList(one);
    

    This will allow you to modify the order or what elemtents are contained independent of the first list.

    Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

    example:

    MyObject value1 = one.get(0);
    MyObject value2 = two.get(0);
    value1 == value2 //true
    value1.setName("hello");
    value2.getName(); //returns "hello"
    

    Edit

    To avoid this you need a deep copy of each element in the list like so:

    List<Torero> one = new ArrayList<Torero>();
    //add elements
    
    List<Torero> two = new Arraylist<Torero>();
    for(Torero t : one){
        Torero copy = deepCopy(t);
        two.add(copy);
    }
    

    with copy like the following:

    public Torero deepCopy(Torero input){
        Torero copy = new Torero();
        copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
    
        return copy;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题