What is AbstractCollection class in Java?

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 29-Mar-2019 11:34:52
Advertisements