compareTo()

整体的意思就是 CompareTo()方法如果返回的负数,就是你比别人小。

Tag
  int count
  String name

所以如果,比如你想通过自己的count去排序。

你就可以这样写


int compareTo(Object o){
      return this.count - ((Tag)o).count;
}

就是说要把自己写在前面,然后去减去就行了


import java.util.Arrays;
class A implements Comparable
{
int i,j;
public A(int a1,int a2)
{
i=a1;
j=a2;
}
public int compareTo(Object obj)
{
int k=((A)obj).i;
if(k>i)
return -1;
else if(k<i)
return 1;
else
return 0;
}
public String toString()
{
return "("+i+","+j+")";
}
}
public class suntest
{
public static void main(String []args)
{
   A []b={new A(5,2),new A(2,3),new A(3,1)};
   Arrays.sort(b);
   System.out.println("排序后"+Arrays.toString(b));
}
}

猜你喜欢

转载自have-life.iteye.com/blog/1842078