本帖最后由 郭军亮 于 2013-5-18 10:22 编辑
package Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet ts=new TreeSet(new myCompare());
Student t1=new Student("lisi9",23);
Student t2=new Student("li",18);
Student t3=new Student("lisi2",23);
Student t4=new Student("lisi9",13);
ts.add(t1);
ts.add(t2);
ts.add(t3);
ts.add(t4);
for(Iterator t=ts.iterator();t.hasNext();){
Student s=(Student)t.next();
System.out.println(s.getName()+"..."+s.getAge());
}
}
}
class Student implements Comparable{
private String name;
private int age;
Student(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
if(!(o instanceof Student))
throw new RuntimeException("it is error!!!");
Student s=(Student) o;
System.out.println(this.getName()+"...compareTo..."+s.getName());
if(this.getAge()>s.getAge())
return 1;
else if(this.getAge()==s.getAge()){
return this.getName().compareTo(s.getName());
}
return -1;
}
}
class myCompare implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if(o1 instanceof Student && o2 instanceof Student)
throw new RuntimeException("The type is not match!!!");//为什么加上这两句话后会发生异常呢?
Student s1=(Student)o1;
Student s2=(Student)o2;
int num=s1.getName().compareTo(s2.getName());
if(num==0)
return s1.getAge()-s2.getAge();
return num;
}
} |