import java.util.*;
class Example
{
public static void main(String args[])
{
TreeSet<Student> mytree=
new TreeSet<Student>(new Comparator<Student>()
{
public int compare(Student a,student b)
{
return a.compareTo(b);
}
});
Student st1,st2,st3,st4;
st1=new Student(90,"zhan ying");
st2=new Student(66,"wang heng");
st3=new Student(86,"zan ying");
st4=new Student(76,"hang heng");
mytree.add(st1);
mytree.add(st2);
mytree.add(st3);
mytree.add(st4);
Iterator<Student> te=mytree.iterator();
while(te.hasNext())
{
Student stu=te.next();
System.out.println(""+stu.name+""+stu.english);
}
}
}
class Student implements Comparable
{
int english =0;
String name;
Student(int e,String n)
{
english=e;name=n;
}
public int compareTo(Object b)
{
Student st=(Student)b;
return(this.english-st.english);
}
}都用到了.他们到底是怎么用的?谢谢了.
class Example
{
public static void main(String args[])
{
TreeSet<Student> mytree=
new TreeSet<Student>(new Comparator<Student>()
{
public int compare(Student a,student b)
{
return a.compareTo(b);
}
});
Student st1,st2,st3,st4;
st1=new Student(90,"zhan ying");
st2=new Student(66,"wang heng");
st3=new Student(86,"zan ying");
st4=new Student(76,"hang heng");
mytree.add(st1);
mytree.add(st2);
mytree.add(st3);
mytree.add(st4);
Iterator<Student> te=mytree.iterator();
while(te.hasNext())
{
Student stu=te.next();
System.out.println(""+stu.name+""+stu.english);
}
}
}
class Student implements Comparable
{
int english =0;
String name;
Student(int e,String n)
{
english=e;name=n;
}
public int compareTo(Object b)
{
Student st=(Student)b;
return(this.english-st.english);
}
}都用到了.他们到底是怎么用的?谢谢了.
可以说一个是自已完成比较,一个是外部程序实现比较的差别而已。
方法有一个this指针指向自己
函数没有this指针,需要两个参数
import java.util.*;
public class AbsComparator implements Comparator {
public int compare(Object o1, Object o2) {
int v1 = Math.abs(((Integer)o1).intValue());
int v2 = Math.abs(((Integer)o2).intValue());
return v1 > v2 ? 1 : (v1 == v2 ? 0 : -1);
}
}可以用下面这个类测试AbsComparator://Test.java
import java.util.*;public class Test {
public static void main(String[] args) { //产生一个20个随机整数的数组(有正有负)
Random rnd = new Random();
Integer[] integers = new Integer[20];
for(int i = 0; i < integers.length; i++)
integers[i] = new Integer(rnd.nextInt(100) * (rnd.nextBoolean() ? 1 : -1)); System.out.println("用Integer内置方法排序:");
Arrays.sort(integers);
System.out.println(Arrays.asList(integers)); System.out.println("用AbsComparator排序:");
Arrays.sort(integers, new AbsComparator());
System.out.println(Arrays.asList(integers));
}
}