What is a Java Collection
Dictionary meaning of Collection is ‘a group of objects accumulated in one location, especially for some purpose’. In java, collection is true realization of the meaning. Sometimes it is also defined in the manner as – It is a way to achieve the concept of ‘Data Structure’ in java.
Collection api is used to store, retrieve, manipulate, and aggregate the data. Typically, they represent data items which are related, such as a phone directory (a mapping of names to phone numbers).
Most of the Java collections are derived from java.util package. Let’s have a look at the 6 core interfaces provided in Java Collection Framework:
Interface Realization or Implementation Classes
In the table presented above, ‘Map’ interface is not extended by java.util.Collection interface but all others are.
java.util.Collections – (ends with s) –
java.util.Collections is a class. It is a utility class that contains all the static methods. The methods of this class throw NullPointerException in case a null object or collection is provided to them. The purpose of this class is to facilitate basic operation within a collection. Most commonly used methods includes – sort(List<T> list), sort (List<T> list, Comparator<? super T> comparator), addAll(Collection <? super T> coll, T… elements), reverse(List<?> list) etc.
Though there are many methods(also known as operations in object oriented world) supported by Collection interface, I am going to highlight a few which are very useful/basic among them.
int size() – Returns the size in terms of number of elements in collection.
Object toArray() – Translates the collection elements into an array.
boolean add(E o) – Adds the given element into collection and returns true if done.
boolean contains(Object o) – Performs the check on collection and if the Object is present in collection, returns true.
boolean remove(Object o) – Removes the given Object from the collection and returns true if removed. Beware of java.util.ConcurrentModificationException while using this method on actual collection.
boolean isEmpty() – Returns true if the collection does not contain any element.
In the next few posts I would discuss about the different interfaces and their implementation classes.