45

我正在实现一个负责订购 java.util.List 的 Java 类。当我使用这个类时,问题就来了。我可以订购列表,但我想复制“原始”列表而不进行修改,以便我可以注册原始列表上所做的每一个更改。排序后的列表包含对象,其中一个字段存储了一个分类 id,这个 id 用列表的索引值更新。

我尝试使用克隆方法,它使列表保持未排序,但对原始列表所做的更改也在克隆列表中更新。

有没有办法实现它?

我的代码:

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

分类方法:

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

2 回答 2

89

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;
}
于 2012-05-04T22:52:31.763 回答
23

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.

于 2012-05-04T22:51:26.747 回答