java TreeSet,
分享于 点击 21145 次 点评:239
java TreeSet,
TreeSet可以对Set集合中的元素进行排序。
底层数据结构:二叉树。
保证元素唯一:comoareTo return 0;
TreeSet排序的第一种方式:让元素自身具备比较性。元素实现Comparable接口覆盖compareTo方法,这种方式也称为元素的自然顺序,或者叫默认顺序。
TreeSet排序的第二种方式:当元素自身不具备比较性时,或者具备的比较性不是所需要的,这时需要让集合自身具备比较性。在集合初始化时,就有了比较方式。
存储自定义对象学生。
记住:排序时,当主要条件相同时,一定要判断一下次要条件。
public class TreeSetDemo { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add(new Student("lisi02", 2)); ts.add(new Student("lisi01", 1)); ts.add(new Student("lisi04", 4)); ts.add(new Student("lisi03", 3)); ts.add(new Student("lisi04", 3)); Iterator it = ts.iterator(); while (it.hasNext()) { Student s = (Student) it.next(); System.out.println(s.getName() + "::" + s.getAge()); } } } class Student implements Comparable { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public int compareTo(Object o) { if (!(o instanceof Student)) throw new RuntimeException("不是学生对象"); Student s = (Student) o; if (this.age > s.age) { return 1; } if (this.age == s.age) { return this.name.compareTo(s.name); } return -1; } }
存入和取出顺序一样:comoareTo return 正数
存入和取出顺序相反:comoareTo return 负数
只存入一个元素:comoareTo return 0
当元素自身不具备比较性,或者具备的比较性不是所需要的,这时需要让容器自身具备比较性,定义比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
public class TreeSetDemo { public static void main(String[] args) { TreeSet ts = new TreeSet(new MyCompare()); ts.add(new Student("lisi02", 2)); ts.add(new Student("lisi01", 1)); ts.add(new Student("lisi04", 4)); ts.add(new Student("lisi03", 3)); ts.add(new Student("lisi04", 3)); Iterator it = ts.iterator(); while (it.hasNext()) { Student s = (Student) it.next(); System.out.println(s.getName() + "::" + s.getAge()); } } } class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } class MyCompare implements Comparator { @Override public int compare(Object o1, Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; int num = s1.getName().compareTo(s2.getName()); if (num == 0) return s1.getAge() - s2.getAge(); return num; } }
当两种方式都存在时以比较器为主。
比较器:定义一个类,实现Comparetor接口,覆盖compare方法。
存储字符串并按长度排序:
字符串本身具备比较性,但它的比较性不是我们所需要的。使用比较器。
public class TreeSetDemo { public static void main(String[] args) { TreeSet ts = new TreeSet(new MyCompare()); ts.add("sd"); ts.add("q"); ts.add("qq"); ts.add("hsaa"); ts.add("ehhhhh"); Iterator it = ts.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } class MyCompare implements Comparator { @Override public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; int num = new Integer(s1.length()).compareTo(new Integer(s2.length())); if (num == 0) { return s1.compareTo(s2); } return num; } }
相关文章
- 暂无相关文章
用户点评