本帖最后由 于星星 于 2012-7-14 21:50 编辑
s1.getScor().compareTo(s2.getScor());,compareTo这个方法是student对象的方法,你现在是s1.getScor()返回值来调用的
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
class student implements Comparable
{
private int age;
private int scor;
private String name;
public student(String name,int age,int scor)
{
this.age=age;
this.scor=scor;
this.name=name;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int getScor()
{
return scor;
}
public int compareTo(Object obj)
{
if(!(obj instanceof student))
throw new RuntimeException();
student s=(student)obj;
if (this.scor>s.scor)
return 1;
if (this.scor==s.scor)
return this.name.compareTo(s.name);
return -1;
}
}
public class TreeSetDemo
{
public static void main(String [] args)
{
TreeSet t=new TreeSet(new Mycompare());//两种方式
t.add(new student("a",20,70));
t.add(new student("b",20,78));
t.add(new student("c",20,80));
t.add(new student("d",20,85));
t.add(new student("e",20,90));
Object obj[] = t.toArray();
for(int i=0;i<obj.length;i++){
student s1 = (student)obj;
System.out.println(s1.getScor()+"排序之前");
}
Arrays.sort(obj,new Mycompare());
for(int i=0;i<obj.length;i++){
student s1 = (student)obj;
System.out.println(s1.getScor()+"排序之后");
}
}
}
class Mycompare implements Comparator
{
public int compare(Object o1,Object o2)
{
student s1=(student)o1;
student s2=(student)o2;
if(s1.getScor()>s2.getScor()){
return -1;
}
if(s1.getScor()>s2.getScor()){
return 1;
}
return 0;
}
}
这里需要用到Arrays工具类的排序方法,然后将实现Comparator接口的对象传进去,在compare方法里面传入两个参数,如果第一个参数大于第二个参数就返回负数,等于返回0,小于返回正整数。
|