Saturday, November 10, 2018

Java Collections - Collection Interface

Greetings!

Collection interface is the base interface for most of the classes in Collection Framework. It mainly contains methods for add, remove and iteration.


public interface Collection<E> {

    boolean add(E element);

    Iterator<E> iterator();

    boolean remove(Object o);

    // ....
}


Other than that this contains a lot of common utility methods.


int size()
boolean isEmpty()
boolean contains(Object obj)
boolean containsAll(Collection<?> c)
boolean equals(Object other)
boolean addAll(Collection<? extends E> from)
boolean remove(Object obj)
boolean removeAll(Collection<?> c)
void clear()
boolean retainAll(Collection<?> c)
Object[] toArray()
<T> T[] toArray(T[] arrayToFill)


Java 8 has introduced new default methods to convert the Collection into a stream.


default Stream<E> stream()
default Stream<E> parallelStream()
default boolean removeIf(Predicate<? super E> filter)


  • There is no concrete implementation of Collection interface. Instead it has several sub interfaces to handle different kind of Collections.
  • Because most of the utility methods are common, there is partially implemented AbstractCollection that other implementation can extend. (this can be removed with Java 8 default methods)



No comments:

Post a Comment