- import java.util.*;
- //由于Student对象不具备比较性,无法存入TreeSet集合中,所以要实现Comparable,实现compareTo方法
- class Student implements Comparable //该接口强制让Student具有比较性
- {
- private String name;
- private int age;
- Student(String name,int age){
- this.name=name;
- this.age=age;
- }
- //实现compareTo方法
- public int compareTo(Object obj){
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象");
- Student t=(Student)obj;
- System.out.println(this.name+".."+t.name);
- if(this.age>t.age) //当调用对象年龄年龄大于比较对象时
- return 1;
- if(this.age==t.age){ //当调用对象年龄等于比较对象时,再比较姓名是否相等
- // System.out.println(this.name+".."+t.name);
- if(this.name.equals(t.name))
- return 0;
- }
- return -1; //年龄小于比较对象返回-1
- }
- String getName(){
- return name;
- }
- int getAge(){
- return age;
- }
- }
-
- class TreeSetTest
- {
- public static void main(String args[]){
-
- TreeSet ts=new TreeSet();
- ts.add(new Student("小白",21));
- ts.add(new Student("小黄",20));
- ts.add(new Student("小黑",21));
- ts.add(new Student("小红",19));
- ts.add(new Student("小白",21));
- /*Exception in thread "main" java.lang.ClassCastException:
- Student cannot be cast to java.lang.Comparable 由于Student对象没有比较性
- */
- Iterator it=ts.iterator();
- while(it.hasNext()){ //打印
- Student s=(Student)it.next();
- sop(s.getName()+".."+s.getAge());
- }
-
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
复制代码
代码不全,重新贴一下 |