elibraryportal Logo

Collection in Java

→ Collection represents a single unit of objects i.e. a group.

→ Collections is a framework that provides an architecture to store and manipulate the group of objects.

→ All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc.

→ Collection is a Interface available in java.util package. many interface such as Set, List, Queue, Deque etc. and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

Collection Framework API consists of following.

  • Interfaces
  • Implementation Classes
  • Algorithms implementations

Top level interface available in Collection Framework API.

  • Collection
  • Map
  • Iterator

Hierarchy of java.util package .

java.util package package contains all the classes and interfaces for Collection framework.

Fig..

Hierarchy Collection

Collection interface Methods

following methods declared in the Collection interface. that is:

No.MethodDescription
1public boolean add(Object element) It adds the given element.
2public boolean addAll(Collection c)It adds all the elements in the given collection.
3public boolean remove(Object element)It remove a single instance of the given element.
4public boolean removeAll(Collection c)It removes all of this collection's elements that are also contained in the given collection(Optional Operation).
5public boolean retainAll(Collection c)is used to delete all the elements of invoking collection except the specified collection.
6public int size()It gets the number of elements in this collection.
7public void clear()It remove all the elements from this collection
8public boolean contains(Object element)is used to search an element.
9public boolean containsAll(Collection c)is used to search the specified collection in this collection.
10public Iterator iterator()returns an iterator.
11public Object[] toArray()converts collection into array.
12public boolean isEmpty()checks if collection is empty.
13public boolean equals(Object element)matches two collection.
14public int hashCode()returns the hashcode number for collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

3 methods in the Iterator interface. They are:

  1. public boolean hasNext() it returns true if iterator has more elements.
  2. public object next() it returns the element and moves the cursor pointer to the next element.
  3. public void remove() it removes the last elements returned by the iterator. It is rarely used.