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

 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 }

 

转载于:https://www.cnblogs.com/Maple-100/p/3220203.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值