public class Test implements Comparable{
private int v1;
private int v2;
public int compareTo(Object o) {
//根据v1的大小
return 0;
}}
LinkedList<Test> test=new LinkedList<Test>();然后向test添加了N个Test对象
在代码的别处,我有时想根据v1的大小对test的元素进行排序,那么只要调用Collections.sort(test);
但是有时又要根据v2的大小对test的元素进行排序,这时候除了自己写排序的实现还有什么办法不?

解决方案 »

  1.   

    你可以给Test 增加一个变量  静态的 布尔型的即可
    再compareTo里面根据这个变量的值来判断用v1 还是v2 
    这样调用sort前,设定一下这个变量的值即可
      

  2.   

    静态变量?绝对不可以!!!!
    如果2个人同时访问的话,正好每个人访问的需要不同的排序方式,会发生什么事情?? 无法预料的结果哦!建议自己编写比较算法,请参考如下代码
     List reList = new ArrayList();
         
      Collections.sort(reList, new Comparator() {   // Parameters:
       // o1 - the first object to be compared.
       // o2 - the second object to be compared.
       // Returns:
       // a negative integer, zero, or a positive integer as the first
       // argument is less than, equal to, or greater than the second.
       // Throws:
       // ClassCastException - if the arguments' types prevent them from
       // being compared by this Comparator.
       public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        return 0;
       }  });