本实例演示往TreeSet集合中存储自定义对象

时间:2022-01-07 04:57:43
 1 package JiHe.Set;
2
3 import java.util.Iterator;
4 import java.util.TreeSet;
5
6 /*
7 * 本实例演示往TreeSet集合中存储自定义对象
8 *
9 * 注意:因为Student不具有比较性,所以需要实现Comparable接口,并且复写接口中的compareTo方法来对其进行排序;
10 */
11 public class TreeObject {
12 public static void main(String[] args) {
13 TreeSet ts = new TreeSet();
14
15 //因为Student不具备有比较性,所以在运行的时候,可能会抛出java.lang.ClassCastException异常
16 ts.add(new Student("zhangSan", 11));
17 ts.add(new Student("lishi", 22));
18 ts.add(new Student("wangWu", 33));
19 ts.add(new Student("zhaoliu", 44));
20
21 Iterator it = ts.iterator();
22 while(it.hasNext()){
23 Student stu = (Student)it.next();
24 System.out.println(stu.getName()+"......"+stu.getAge());
25 }
26 }
27 }
28
29 class Student implements Comparable { //Comparable该接口强制让学生类具备比较性
30 private String name;
31 private int age;
32
33 Student(String name, int age) {
34 this.name = name;
35 this.age = age;
36 }
37
38 public String getName() {
39 return name;
40 }
41
42 public int getAge() {
43 return age;
44 }
45
46 //复写compareTo方法;返回:负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。
47 public int compareTo(Object o) {
48 if(!(o instanceof Student))
49 throw new RuntimeException("不是学生对象");
50
51 //将传递过来的对象强转为学生对象
52 Student s = (Student)o;
53 System.out.println(this.name+"...comparableTo..."+s.name);
54 if(this.age > s.age){
55 return 1; //如果当前对象大于了传入对象的age,则返回一个正数,表示大于
56 }else if(this.age == s.age){
57 return 0; //如果当前对象等于传递对象的age,则返回一个0,表示等于
58 }else{
59 return -1; //如果以上两种情况都不是,则返回一个负数,表示当前对象小于传递的对象
60 }
61 }
62 }