/* * Set:无序,不可以重复元素 * |--HashSet:数据结构是哈希表。线程是非同步的 * 保证元素唯一性的原理:判断元素的hashCode值是否相同。 * 如果相同,会继续判断元素的equals方法是否为true。 * |--TreeSet:可以对Set集合中的元素进行排序 * 底层数据结构是二叉树 * 保证元素唯一性的依据是: compareTo方法return的值。 正数,大,0,等,负数,小 * * TreeSet排序的第一种方式:让元素自身具备比较性。 * 元素需要实现Comparable的接口,覆盖compareTo方法。 * 这种方式也称为元素的自然排序,或者叫做默认顺序。 * * * * * 需求: * 往 TreeSet集合中存储自定义对象学生, * 然后按照学生的年龄进行排序 * * 记住,排序时,当主要条件相同时,一定要判断次要条件 */ package test.itheima; import java.util.Iterator; import java.util.TreeSet; public class TreeSetDemo { /** * @param args */ public static void main(String[] args) { TreeSet<Student> ts = new TreeSet<Student>(); ts.add(new Student("lisi22", 22)); ts.add(new Student("lisi20", 20)); ts.add(new Student("lisi40", 40)); ts.add(new Student("lisi30", 30)); ts.add(new Student("lisi36", 36)); ts.add(new Student("lisi90", 90)); ts.add(new Student("lisi50", 50)); Iterator it = ts.iterator(); while (it.hasNext()) { Student stu = (Student) it.next(); System.out.println(stu.getName() + " .... " + stu.getAge()); } } } class Student implements Comparable { private String name; private int age; Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } @Override public int compareTo(Object o) { if (!(o instanceof Student)) { throw new RuntimeException("不是学生对象"); } Student s = (Student) o; System.out.println(this.name + "---compare to---" + s.name); if (this.age != s.age) { System.out.println(this.age - s.age); return this.age - s.age; } else { // if(this.name.equals(s.name)){ // return 0; // } // return 1; System.out.println("--- "+(this.name.compareTo(s.name))); return this.name.compareTo(s.name); } } }
[黑马程序员]集合--TreeSet
最新推荐文章于 2017-10-11 22:18:00 发布