集合 API 整理

2017-03-18  本文已影响0人  Draper

TreeSet

将元素添加到集合的正确位置上使用 TreeSet 是一个不错的选择(排序)

对象的比较

对象即元素,只要实现了 Comparable 接口即可对对象进行比较

public interface Comparable<T> {
    int compareTo(T other);
}

调用 a.compareTo(b)

假设是两个x学生进行比较,比较的是 id

public class Student implements Comparable<Student> {
    private int id;

    @Override
    public int compareTo(Student other) {
        //也可 return Integer.compare(id, other.id);
        return id - other.id;//从小到大排序,反之 return other.id - id;
    }
}

但是注意 如果比较的是比较长的数字可能会导致 id - other.id 溢出

还有很多关于排序很有用的接口

public interface Comparator<T>{

    /**
     * 将两个对象进行比较,
     * 如果 a 位于 b 之前则返回负值;
     * 如果两个对象处于相同位置则后返回 0;
     * 如果 a 位于 b 之后返回正值
     */
    int compare(T a, T b);
}
/**
* 同时也要实现 Comparable 接口
*/
public interface SortedSet<E> {

    /**
     * 返回最小的元素
     */
    E first();

    /**
     * 返回最大的元素
     */
    E last();

}
public interface Navigable<E> {

    /**
     * 返回大于 value 的最小元素
     */
    E higher(E value);

    /**
     * 返回小于 value 的最大元素
     */
    E lower(E value);

    /**
     * 返回大于等于 value 的最小元素
     */
    E celling(E value);

    /**
     * 返回小于等于 value 的最大元素
     */
    E floor(E value);

    /**
     * 删除并返回这个集合中的最大元素, 为空返回 null
     * @return
     */
    E poolFirst();

    /**
     * 删除并返回这个集合中的最小元素, 为空返回 null
     */
    E poolLast();

    /**
     * 返回一个按照第几按顺序遍历集合中元素的迭代器
     */
    Iterator<E> descendingIterator();
}
上一篇 下一篇

猜你喜欢

热点阅读