Comparable接口(了解)

缺省情况下,TreeSet中的元素会采用自然排序(从小到大),此时要求元素对象必须实现java.util.Comparable接口,大多数JDK自带的类都实现了该接口,比如八大包装类和String。

TreeSet会调用元素的compareTo方法来比较元素的大小关系,然后将集合元素按照升序排列。

public interface Comparable<T> {

    public int compareTo(T o);

}

比较规则,拿当前元素和另一个元素做比较:

+ this  >    o:返回正整数   1 ,优先级较高

+ this  <    o:返回负整数  -1 ,优先级较低

+ this  ==  o: 返回    0    ,此时认为两个对象为同一个对象。

此时compareTo方法返回0,则认为两个对象是同一个对象,返回正数排前面,返回负数排后面。

如果我们自定义一个类,需要存储到TreeSet中,此时我们需要让该类实现Comparable接口,并覆盖compareTo方法,在该方法编写比较规则。

需求:按照用户的年龄从小到大排序

class User implements java.lang.Comparable<User> {

    private String name;

    private int age;

    public User(String name, int age) {

        this.name = name;

        this.age = age;

    }

    //比较规则

    public int compareTo(User o) {

        if (this.age > o.age) {

            return 1;

        } else if (this.age < o.age) {

            return -1;

        }

        return 0;

    }

    public String toString() {

        return "User [name=" + name + ", age=" + age + "]";

    }

}

public class ComparableDemo{

    public static void main(String[] args) {

        Set<User> set = new TreeSet<>();

        set.add(new User("stef", 28));

        set.add(new User("will", 17));

        set.add(new User("allen", 15));

        set.add(new User("Lucy", 22));

        System.out.println(set);

    }

}

输出结果:

[User [name=allen, age=15], User [name=will, age=17], User [name=Lucy, age=22], User [name=stef, age=28]]

第一步:第一个节点进去,直接作为根节点,无需比较

第二步:第二个节点进去和第一个节点作比较,此时的this表示第二个节点,如果compareTo返回-1,则插入节点往左边走。

第三步:第三个节点进去和第一个节点做比较,返回-1,再和第二个节点做比较。

第四步:由于TreeSet是平衡二叉树,如果树不平衡,会对节点进行调整。

第五步:第四个节点进去先和will比较,再和stef比较。

Comparator接口(了解)

TreeSet除了默认支持自然排序外,还支持自定义排序,此时需要在构建TreeSet对象时传递java.util.Comparator接口的实现类对象,Comparator表示比较器,里面封装比较规则。

public interface Comparator<T> {

    int compare(T o1, T o2);

}

此时compare方法返回0,则认为两个对象是同一个对象,返回正数排前面,返回负数排后面。

需求:根据用户的名字长度排序,如果名字相同按照年龄排序。

class User {

    private String name;

    private int age;

    public User(String name, int age) {

        this.name = name;

        this.age = age;

    }

    public int getAge() {

        return age;

    }

    public String getName() {

        return name;

    }

    public String toString() {

        return "User [name=" + name + ", age=" + age + "]";

    }

}

public class App {

    public static void main(String[] args) {

        Set<User> set = new TreeSet<>(**new NameLengthComparator()**);

        set.add(new User("James", 30));

        set.add(new User("Bryant", 22));

        set.add(new User("Allen", 28));

        set.add(new User("Will", 17));

        System.out.println(set);//

    }

}

class NameLengthComparatorimplements java.util.Comparator<User> {

    public int compare(User o1, User o2) {

        int ret = o1.getName().length() - o2.getName().length();

        if (ret > 0) {

            return 1;

        } else if (ret < 0) {

            return -1;

        } else {

            if (o1.getAge() > o2.getAge()) {

                return 1;

            } else if (o1.getAge() < o2.getAge()) {

                return -1;

            } else {

                return 0;

            }

        }

    }

}

输出结果:

[User [name=Will, age=17], User [name=Allen, age=28], User [name=James, age=30], User [name=Bryant, age=22]]

小结:HashSet做等值查询效率高,TreeSet做范围查询效率高,在开发中一般使用HashSet就可以了。