The java.util.AbstractCollection class helps to minimize the efforts of the implementation of java.util.Collection interface by providing skeletal implementation.


Both the AbstractCollection class and Collection interface were added in Java 1.2 version.

The java.lang.Iterable interface was added in Java 1.5 and extended by java.util.Collection interface to provide Iterator support on collections.

Both modifiable and unmodifiable collections are supported by the java.util.AbstractCollection class.


To implement a Modifiable Collection we need to override two methods
  1. To implement a modifiable collection using AbstractCollection class we need to additionally override this class's add method otherwise an UnsupportedOperationException will be thrown.

  2. Iterator returned by the iterator method must additionally implement its remove method

To implement a Unmodifiable Collection we need to do the following
  1. Extend AbstractCollection class and provide implementations for the iterator and size methods.
  2. The iterator returned by the iterator method must implement hasNext and next.

Below is the sample program using AbstractCollection class.

package com.learning.collection;

import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.HashSet;

public class AbstractCollectionMain {

	public static void main(String[] args) {
		
		//New unordered collection 
		//HashSet is an unordered collection
		AbstractCollection<Object> unorderedAbsColl = new HashSet<Object>();
		
		unorderedAbsColl.add("One");
		unorderedAbsColl.add("Two");
		unorderedAbsColl.add("Three");
		unorderedAbsColl.add("Four");
		unorderedAbsColl.add("Five");

		System.out.println("UnorderedAbsColl Output = " + unorderedAbsColl);
		
		
		
		
		//new ordered collection
		//ArrayList is an ordered collection
		AbstractCollection<String> orderedAbsColl = new ArrayList<String>();
		
		orderedAbsColl.add("One");
		orderedAbsColl.add("Two");
		orderedAbsColl.add("Three");
		orderedAbsColl.add("Four");
		orderedAbsColl.add("Five");

		System.out.println("OrderedAbsColl Output = " + orderedAbsColl);
		
		
	}

}

Sample Program Output

UnorderedAbsColl Output = [Five, One, Four, Two, Three]
OrderedAbsColl Output = [One, Two, Three, Four, Five]