How to copy java.util.list Collection

前端 未结 2 1806
半阙折子戏
半阙折子戏 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 one = new ArrayList();
    //add elements
    
    List two = new Arraylist();
    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;
    }
    

提交回复
热议问题