首页 > 代码库 > TreeSet 排序

TreeSet 排序

 

 1 class Person1 implements Comparable <Person1>{ 2     private Float height; 3     private String name; 4      5     Person1(float height) 6     { 7         this.height=height; 8     } 9 10     public Float getHeight() {11         return height;12     }13 14     public void setHeight(float height) {15         this.height = height;16     }17 18     public String getName() {19         return name;20     }21 22     public void setName(String name) {23         this.name = name;24     }25 26     @Override27     public int compareTo(Person1 p) {28         if(this.getHeight()<p.getHeight()){29             return 1;30             31         }else if(this.getHeight()>p.getHeight()){32             return -1;33         }else{34             return 0;    35         }36         37     }38 }39 40 41 public class Question3_1 {42 43     public static void main(String[] args) {44         Person1 p1=new Person1(23.4f);45         p1.setName("Stud1");46         Person1 p2=new Person1(2.34f);47         p2.setName("Stud2");48         Person1 p3=new Person1(34.32f);49         p3.setName("Stud3");50         Person1 p4=new Person1(56.45f);51         p4.setName("Stud4");52         Person1 p5=new Person1(21.4f);53         p5.setName("Stud5");54         55       56         TreeSet<Person1> al=new TreeSet<Person1>();57         al.add(p1);58         al.add(p2);59         al.add(p3);60         al.add(p4);61         al.add(p5);62         63        65         for(Person1 p:al)66             System.out.println(p.getName()+" "+p.getHeight());67 68     }69 70 }

 

 

 

结果:

Stud4 56.45
Stud3 34.32
Stud1 23.4
Stud5 21.4
Stud2 2.34

TreeSet 中的对象时自定义对象时,需实现Comparable 接口

 

Exception in thread "main" java.lang.ClassCastException: com.cn.aug26.Person1 cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(TreeMap.java:1188)
    at java.util.TreeMap.put(TreeMap.java:531)
    at java.util.TreeSet.add(TreeSet.java:255)
    at com.cn.aug26.Question3_1.main(Question3_1.java:64)

TreeSet 排序