What is AbstractCollection class in Java?


The AbstractCollection class provides an implementation of the Collection interface. This is done to minimize the effort in the implementation of this interface.

For an unmodifiable collection

Extend this class and provide implementations for the iterator and size methods.

For modifiable collection

Additionally override the add() method of the class. The iterator method returns the iterator and it must implement the remove() method.

The syntax is as follows.

public abstract class AbstractCollection<E>
extends Object
implements Collection<E>

Here, Object is the root of the class hierarchy and Collection is a group of objects.

To work with AbstractCollection class in Java, import the following package.

import java.util.AbstractCollection;

Let us now see an example to implement the AbstractCollection class in Java.

Example

 Live Demo

import java.util.ArrayList;
import java.util.AbstractCollection;
public class Demo {
   public static void main(String[] args) {
      AbstractCollection<Object> absCollection = new ArrayList<Object>();
      absCollection.add("This");
      absCollection.add("is");
      absCollection.add("demo");
      absCollection.add("text");
      System.out.println("Displaying elements in the AbstractCollection: " + absCollection);
   }
}

Output

Displaying elements in the AbstractCollection: [This, is, demo, text]

Updated on: 30-Jul-2019

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements