AbstractSet in Java

  • September 12, 2022
  • Java
java thread class

AbstractSet is a Java Collection Framework class that implements the Collection interface and extends the AbstractCollection class. It implements the Set interface in its most basic form. This class does not override any of the AbstractCollection class’s implementations, but instead adds equals() and hashCode() methods.

Class Hierarchy:
 ↳ java.util.AbstractCollection<E>
    ↳ Class AbstractSet<E>
public abstract class AbstractSet<E>
extends AbstractCollection<E>
implements Set<E>

Where E is the type of elements maintained by this Set.

Constructor of AbstractSet Class :

protected AbstractSet(): it is the default constructor, but being protected, it doesn’t allow the creation of an AbstractSet object.

Methods of AbstractSet:
Method Description
boolean equals(Object o)Checks for equality between the specified object and this set.
int hashCode()This function returns the hash code value for this set.
boolean removeAll(Collection<?> c)Removes all of the elements from this set that are in the specified collection (optional operation).

import java.util.*;

public class Coderz {

	public static void main(String[] args) throws Exception

		try {

			// Creating an empty TreeSet of integer type
			AbstractSet<Integer> abset
				= new TreeSet<Integer>();

			// Populating above TreeSet
			// using add() method

			// Printing the elements inside TreeSet
			System.out.println("AbstractSet before "
							+ "removeAll() operation : "
							+ abset);

			// Creating an ArrayList of integer type
			Collection<Integer> arrlist2
				= new ArrayList<Integer>();

			// Adding elements to above ArrayList

			// Printing the ArrayList elements
			System.out.println("Collection Elements"
							+ " to be removed : "
							+ arrlist2);

			// Removing elements from AbstractSet specified
			// using removeAll() method

			// Printing the elements of ArrayList
			System.out.println("AbstractSet after "
							+ "removeAll() operation : "
							+ abset);

		// Catch block to handle the exceptions
		catch (NullPointerException e) {

			// Display exception on console
			System.out.println("Exception thrown : " + e);
AbstractSet before removeAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be removed : [1, 2, 3]
AbstractSet after removeAll() operation : [4, 5]

Note: also read about the CopyOnWriteArrayList class

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.



1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *