本文主要是介绍Collections.EMPTY_LIST 和 Collections.emptyList()的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Collections中的EMPTY_LIST 和 emptyList 其实通过源码查看,他们最终都是同一个final的不变的实例对象
public static final List EMPTY_LIST = new EmptyList<>();
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST; }
在Collections中自定义了一个内部类EmptyList,该内部类继承了AbstractList的抽象类,拥有了list的数据结构
并重写了get方法
private static class EmptyList<E> extends AbstractList<E>
implements RandomAccess, Serializable {private static final long serialVersionUID = 8842843931221139166L;public Iterator<E> iterator() {return emptyIterator();}public ListIterator<E> listIterator() {return emptyListIterator();}public int size() {return 0;}public boolean isEmpty() {return true;}public boolean contains(Object obj) {return false;}public boolean containsAll(Collection<?> c) { return c.isEmpty(); }public Object[] toArray() { return new Object[0]; }public <T> T[] toArray(T[] a) {if (a.length > 0)a[0] = null;return a;}
//重写该get方法,禁止该方法去获取对象,使用时抛出下标越界public E get(int index) {throw new IndexOutOfBoundsException("Index: "+index);}public boolean equals(Object o) {return (o instanceof List) && ((List<?>)o).isEmpty();}public int hashCode() { return 1; }@Override public boolean removeIf(Predicate<? super E> filter) {Objects.requireNonNull(filter);return false;}@Override public void replaceAll(UnaryOperator<E> operator) {Objects.requireNonNull(operator);}@Override public void sort(Comparator<? super E> c) {}// Override default methods in Collection @Override public void forEach(Consumer<? super E> action) {Objects.requireNonNull(action);}@Override public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }// Preserves singleton property private Object readResolve() {return EMPTY_LIST;} }
这篇关于Collections.EMPTY_LIST 和 Collections.emptyList()的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!