1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 本实例演示往TreeSet集合中存储自定义对象

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

时间:2021-12-10 20:49:37

相关推荐

本实例演示往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 {12public 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该接口强制让学生类具备比较性30private String name;31private int age;32 33Student(String name, int age) {34 this.name = name;35 this.age = age;36}37 38public String getName() {39 return name;40}41 42public int getAge() {43 return age;44}4546//复写compareTo方法;返回:负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。 47public 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 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。