- import java.util.*;
- /* Set 无序,不可以重复元素.
- |--HashSet
- 数据结构式哈希表.线程时非同步的.
- 保证元素唯一性的原理:判断元素的hashCode值是否相同.
- 如果相同,还会继续判断元素的equals方法,是否为true.
- |--TreeSet
- 可以对Set集合中的元素进行排序.
- 底层数据结构是二叉树.
- 保证元素唯一性的依据:
- compareTo方法 return 0.
- TreeSet排序的第一种方式:让元素自身具备比较性.
- 元素需要实现comparable接口,覆盖compareTo方法.
- 这种方式也成为自然顺序,或者叫默认顺序.
- */
- class TreeSetDemo {
- public static void main(String[] args) {
- TreeSet ts = new TreeSet();
-
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi002",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi08",19));
-
- for(Iterator it = ts.iterator(); it.hasNext(); ) {
-
- Student s = (Student)it.next();
- sop(s.getName() + "===" + s.getAge());
- }
-
- }
-
- public static void sop(Object obj) {
- System.out.println(obj);
- }
- }
- 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;
- }
-
- public int compareTo(Object obj) {
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象!");
-
- Student s = (Student)obj;
-
- if(this.age > s.age)
- return 1;
-
- if(this.age == s.age)
- return this.name.compareTo(s.name);
-
- return -1;
- }
- }
复制代码- import java.util.*;
- /*
- 当元素自身不具备比较性,或者具备的比较性不是所需要的。
- 这时需要让容器自身具备比较性。
- 定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
- 当两种排序都存在时,以比较器为主。
- 定义一个类,实现Comparator接口,覆盖compare方法。
- */
- public class TreeSetDemo2 {
- public static void main(String[] args) {
- TreeSet ts = new TreeSet(new MyCompare());
-
- ts.add(new Student("Hu",20));
- ts.add(new Student("Li",25));
- ts.add(new Student("Zheng",28));
- ts.add(new Student("Wang",29));
- ts.add(new Student("Song",21));
- ts.add(new Student("Song",21));
-
- for(Iterator it = ts.iterator(); it.hasNext(); ) {
- Student s = (Student)it.next();
- TreeSetDemo.sop(s.getName()+"==="+s.getAge());
- }
- }
- }
- class MyCompare implements Comparator {
- public int compare(Object o1, Object o2) {
-
- Student s1 = (Student)o1;
- Student s2 = (Student)o2;
-
- Integer num = s1.getName().compareTo(s2.getName());
-
- if(num == 0)
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
-
- return num;
- }
- }
复制代码- import java.util.*;
- /*
- 练习:按照字符串长度排序。
- 字符串本身具备比较性。但是它的比较方式不是所需要的。
- 这时就只能使用比较器。
- */
- public class TreeSetTest {
- public static void main(String[] args) {
-
- TreeSet ts = new TreeSet(new StrLenComparator());
-
- ts.add("abcd");
- ts.add("cc");
- ts.add("cba");
- ts.add("aaa");
- ts.add("z");
- ts.add("hahaha");
-
- for(Iterator it = ts.iterator(); it.hasNext(); ) {
- TreeSetDemo.sop(it.next());
- }
- }
- }
- class StrLenComparator implements Comparator {
- 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;
- }
- }
复制代码 |
|