Collections.emptyList cannot add?

and things like emptyMap can"t add elements, so what are these static methods for?

Mar.15,2021

first of all, Please check the api document :

if you encounter api problems.

clipboard.png
clipboard.png

these methods are usually used by me personally:
for example, there is a method that executes some logic to return a list, such as querying a database to return query results. So when there is nothing, there are two choices: return null, or return emptyList. If null, is returned directly, then the caller needs to be null, while the caller who returns emptyList, can operate directly.

these methods are an implementation of " empty object design pattern . It is similar to Optional introduced by java 8.


use empytList ah, emptyMap when all you need is an immutable empty list. There is another point you can take a look at the source code:

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;
    }

    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;
    }
}

EmptyList there are no member variables used to describe list information and save list elements. Getting EmptyList objects can save unnecessary space compared to directly new a ArrayList or LinkedList .

Menu