[java] How to copy java.util.list Collection

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" list without modification so that I could register every change made on the original list. The sorted list contains object and one of its fields stores a classification id, and this id it is updated with the index value of the list.

I tried to use clone method and it keeps the list unsorted but the changes made on original list are updated in the clone list too.

Is there any way to accomplish it?

My Code:

List<Torero> listaTorero = tbTlgTorerolHome.findByExample(new Torero());
List<Torero> listaToreroTemp = ((List<Torero>) ((ArrayList<Torero>) listaTorero).clone()); 

Clasificacion clasificacion = new Clasificacion();

Iterator<Torero> iterTorero = clasificacion.getClasificacion(listaTorero, torero).iterator(); //Sorting List

A Clasificacion method:

public List<Torero> getClasificacion(List<Torero> listaToreroTemp, Torero torero)
{

    List<Torero> listaTorero = new ArrayList<Torero>();

    Collections.sort(listaToreroTemp,new ToreroClasifiacionComparator());

    Iterator<Torero> iterTorero = listaToreroTemp.iterator();
    int index=1;
    while(iterTorero.hasNext())
    {
        Torero toreroTemp = iterTorero.next();
        toreroTemp.setNumClasificacion(index);
        listaTorero.add(toreroTemp);
        index=index+1;
    }
    return listaTorero;
}

This question is related to java clone

The answer is


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;
}

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.