Java源码学习(JDK 11)——java.util.Collections

定义

package java.util;

public class Collections {
    // Suppresses default constructor, ensuring non-instantiability.
    private Collections() {
    }
}
  • 工具类,辅助实现集合相关操作。
  • 构造器私有,保证无法实例化,使用时直接使用静态方法。
  • 方法被 static 修饰。

属性

// 门限
private static final int BINARYSEARCH_THRESHOLD   = 5000;
private static final int REVERSE_THRESHOLD        =   18;
private static final int SHUFFLE_THRESHOLD        =    5;
private static final int FILL_THRESHOLD           =   25;
private static final int ROTATE_THRESHOLD         =  100;
private static final int COPY_THRESHOLD           =   10;
private static final int REPLACEALL_THRESHOLD     =   11;
private static final int INDEXOFSUBLIST_THRESHOLD =   35;

// 空集合
public static final Map EMPTY_MAP = new EmptyMap<>();
public static final List EMPTY_LIST = new EmptyList<>();
public static final Set EMPTY_SET = new EmptySet<>();

// Random 类 shuffle 方法使用
private static Random r;
  • 门限属性主要针对 sequential 的 List,如 LinkedList。
    List 分为 AccessRandom 的 List,可随机访问,如 ArrayList;另一种是上述的 sequential 类型。
    针对这两个不同的类型,需要两种不同的算法。
    通常来说,针对可随机访问列表的算法效率要高一些,sequential list 长度如果比较小的话,也可以使用这种算法。
    该门限通常就是 sequential list 是否使用该算法的分界点。

方法

  • addAll 添加全部
public static <T> boolean addAll(Collection<? super T> c, T... elements) {
    boolean result = false;
    for (T element : elements)
        result |= c.add(element);
    return result;
}
  • asLifoQueue 将 Deque 转为 Stack(LIFO)
/**
Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
{@link Queue}. Method {@code add} is mapped to {@code push},
{@code remove} is mapped to {@code pop} and so on. This
view can be useful when you would like to use a method
requiring a {@code Queue} but you need Lifo ordering.
 */
public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
    return new AsLIFOQueue<>(Objects.requireNonNull(deque));
}

// 通过内部类实现
static class AsLIFOQueue<E> extends AbstractQueue<E>
        implements Queue<E>, Serializable {
    private final Deque<E> q;
    AsLIFOQueue(Deque<E> q)                     { this.q = q; }
    public boolean add(E e)                     { q.addFirst(e); return true; }
    public boolean offer(E e)                   { return q.offerFirst(e); }
    public E poll()                             { return q.pollFirst(); }
    public E remove()                           { return q.removeFirst(); }
    public E peek()                             { return q.peekFirst(); }
    public E element()                          { return q.getFirst(); }

    // ...
}

// AsLIFOQueue 的添加元素和删除元素都是对头元素操作
  • binarySearch 二分搜索
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {
    if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
        return Collections.indexedBinarySearch(list, key);
    else
        return Collections.iteratorBinarySearch(list, key);
}

// 通过 ListItera 获取列表元素
private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) {
    int low = 0;
    int high = list.size()-1;
    ListIterator<? extends Comparable<? super T>> i = list.listIterator();

    while (low <= high) {
        int mid = (low + high) >>> 1;
        Comparable<? super T> midVal = get(i, mid);
        int cmp = midVal.compareTo(key);

        if (cmp < 0)
            low = mid + 1;
        else if (cmp > 0)
            high = mid - 1;
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found
}

private static <T> T get(ListIterator<? extends T> i, int index) {
    T obj = null;
    int pos = i.nextIndex();
    if (pos <= index) {
        do {
            obj = i.next();
        } while (pos++ < index);
    } else {
        do {
            obj = i.previous();
        } while (--pos > index);
    }
    return obj;
}

// Collections.indexedBinarySearch 算法与之类似 但直接通过 list.get 获取元素

// binarySearch 还有一个带有比较器的重载方法 实现类似
  • checkedCollection 获取一个动态类型安全的集合视图
    相应地 还有 checkedMap
public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) {
    return new CheckedCollection<>(c, type);
}

// 通过内部类实现
static class CheckedCollection<E> implements Collection<E>, Serializable {
    final Collection<E> c;
    final Class<E> type;

    // 在添加或者复制等操作前进行类型检查
    @SuppressWarnings("unchecked")
    E typeCheck(Object o) {
        if (o != null && !type.isInstance(o))
            throw new ClassCastException(badElementMsg(o));
        return (E) o;
    }

    // ...
}
  • copy 列表复制
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
    int srcSize = src.size();
    if (srcSize > dest.size())
        throw new IndexOutOfBoundsException("Source does not fit in dest");

    if (srcSize < COPY_THRESHOLD ||
        (src instanceof RandomAccess && dest instanceof RandomAccess)) {
        for (int i=0; i<srcSize; i++)
            dest.set(i, src.get(i));
    } else {
        ListIterator<? super T> di=dest.listIterator();
        ListIterator<? extends T> si=src.listIterator();
        for (int i=0; i<srcSize; i++) {
            di.next();
            di.set(si.next());
        }
    }
}
  • disjoint 判断两个集合是否没有交集
public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
	// ...
	for (Object e : iterate) {
        if (contains.contains(e)) {
           // Found a common element. Collections are not disjoint.
            return false;
        }
    }

    // No common elements were found.
    return true;
}
  • emptyEnumeration 返回空枚举
    相应地 还有 emptyMap
public static <T> Enumeration<T> emptyEnumeration() {
    return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
}

// 内部类实现
  • enumeration 返回枚举
public static <T> Enumeration<T> enumeration(final Collection<T> c) {
    return new Enumeration<T>() {
        private final Iterator<T> i = c.iterator();

        public boolean hasMoreElements() {
            return i.hasNext();
        }

        public T nextElement() {
            return i.next();
        }
    };
}
  • fill 列表填充
// 同样分为两种方法 利用 list.set 或者 ListIterator.set
public static <T> void fill(List<? super T> list, T obj) { /* */ }
  • frequency 返回集合中特定对象出现的次数
public static int frequency(Collection<?> c, Object o) { /* */ }
  • indexOfSubList target list 在 source list 中首次出现的位置
public static int indexOfSubList(List<?> source, List<?> target) { /**/ }
  • lastIndexOfSubList target list 在 source list 中最后出现的位置
public static int lastIndexOfSubList(List<?> source, List<?> target) { /* */ } 
  • list Enumeration 转 ArrayList
public static <T> ArrayList<T> list(Enumeration<T> e) {
    ArrayList<T> l = new ArrayList<>();
    while (e.hasMoreElements())
        l.add(e.nextElement());
    return l;
}
  • max 最大值
// 利用迭代器实现 
// 还有一个带比较器的方法重载
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { /* */ }
  • min 最小值
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { /* */ }
  • nCopies 元素复制 n 倍得到一个 List
public static <T> List<T> nCopies(int n, T o) {
    if (n < 0)
        throw new IllegalArgumentException("List length = " + n);
    return new CopiesList<>(n, o);
}

// 通过内部类实现
private static class CopiesList<E> extends AbstractList<E> implements RandomAccess, Serializable {
    final int n;		// 只保存元素和数量
    final E element;

    CopiesList(int n, E e) {
        assert n >= 0;
        this.n = n;
        element = e;
    }

    public boolean contains(Object obj) {
        return n != 0 && eq(obj, element);
    }

    public int indexOf(Object o) {
        return contains(o) ? 0 : -1;
    }

    // ...
}
  • newSetFromMap 返回一个 Map 的底层 Set
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
    return new SetFromMap<>(map);
}

// 内部类实现
private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable {
    private final Map<E, Boolean> m;  // The backing map
    private transient Set<E> s;       // Its keySet

    SetFromMap(Map<E, Boolean> map) {
        if (!map.isEmpty())
            throw new IllegalArgumentException("Map is non-empty");
        m = map;
        s = map.keySet();
    }

    // ...
}
// 使用 可以通过这个方法创建 jdk 中不存在的 set
Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(64));
  • replaceAll List 替换值
// 同样分为两种方法 利用 list.set 或者 ListIterator.set
public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) { /* */ }
  • reverse List 翻转
public static void reverse(List<?> list) {
    int size = list.size();
    if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
            swap(list, i, j);
    } else {
        ListIterator fwd = list.listIterator();
        ListIterator rev = list.listIterator(size);
        for (int i=0, mid=list.size()>>1; i<mid; i++) {
            Object tmp = fwd.next();
            fwd.set(rev.previous());
            rev.set(tmp);
        }
    }
}
  • reverseOrder 返回一个反序的比较器
public static <T> Comparator<T> reverseOrder() {
    return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
}

// 内部类实现
private static class ReverseComparator implements Comparator<Comparable<Object>>, Serializable {

    static final ReverseComparator REVERSE_ORDER = new ReverseComparator();

    public int compare(Comparable<Object> c1, Comparable<Object> c2) {
        return c2.compareTo(c1);
    }

    @Override
    public Comparator<Comparable<Object>> reversed() {
        return Comparator.naturalOrder();
    }

    // ...
}

// 还有一个带有比较器的重载函数
  • rotate List 旋转
public static void rotate(List<?> list, int distance) {
    if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
        rotate1(list, distance);
    else
        rotate2(list, distance);
}

private static <T> void rotate1(List<T> list, int distance) {
    int size = list.size();
    if (size == 0)
        return;
    distance = distance % size;
    if (distance < 0)
        distance += size;	// 改为向右移动
    if (distance == 0)
        return;

    // 原地旋转

    // nMoved 为移动次数
    for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
        T displaced = list.get(cycleStart);	// 即将移动的元素
        int i = cycleStart;
        do {
            i += distance;	// 新位置
            if (i >= size)
                i -= size;
            displaced = list.set(i, displaced);
            nMoved ++;
        } while (i != cycleStart);
    }
}

private static void rotate2(List<?> list, int distance) {
    int size = list.size();
    if (size == 0)
        return;
    int mid =  -distance % size;
    if (mid < 0)
        mid += size;
    if (mid == 0)
        return;

    reverse(list.subList(0, mid));
    reverse(list.subList(mid, size));
    reverse(list);
}
  • shuffle 随机交换 打乱顺序
public static void shuffle(List<?> list) {
    Random rnd = r;
    if (rnd == null)
        r = rnd = new Random(); // harmless race.
    shuffle(list, rnd);
}

public static void shuffle(List<?> list, Random rnd) { /* */ }
  • singleton 只包含 1 个元素的集合
    相应地 还有 singletonList
public static <T> Set<T> singleton(T o) { /* */ }
  • sort 排序
// 直接调用 list.sort 方法
public static <T extends Comparable<? super T>> void sort(List<T> list) {
    list.sort(null);
}

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}
  • swap 交换
public static void swap(List<?> list, int i, int j) {
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}
  • synchronizedCollection 同步集合
    相应地 还有 synchronizedList
public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
    return new SynchronizedCollection<>(c);
}

// 内部类实现 方法加上同步
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
    final Collection<E> c;  // Backing Collection
    final Object mutex;     // Object on which to synchronize

    SynchronizedCollection(Collection<E> c) {
        this.c = Objects.requireNonNull(c);
        mutex = this;
    }

    SynchronizedCollection(Collection<E> c, Object mutex) {
        this.c = Objects.requireNonNull(c);
        this.mutex = Objects.requireNonNull(mutex);
    }

    public int size() {
        synchronized (mutex) {return c.size();}
    }
}
  • unmodifiableCollection 返回一个不可修改的集合
    相应地 还有 unmodifiableMap
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
    return new UnmodifiableCollection<>(c);
}

// 内部类实现
static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
    final Collection<? extends E> c;

    UnmodifiableCollection(Collection<? extends E> c) {
        if (c==null)
            throw new NullPointerException();
        this.c = c;
    }

    public int size()                          {return c.size();}

    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }
  
  	// ...
}
posted @ 2020-05-28 22:10  JL916  阅读(232)  评论(0编辑  收藏  举报