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.lang.Object
 ↳ java.util.AbstractCollection<E>
    ↳ Class AbstractSet<E>
Syntax:
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).
Example:

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
			abset.add(1);
			abset.add(2);
			abset.add(3);
			abset.add(4);
			abset.add(5);

			// 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
			arrlist2.add(1);
			arrlist2.add(2);
			arrlist2.add(3);

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

			// Removing elements from AbstractSet specified
			// using removeAll() method
			abset.removeAll(arrlist2);

			// 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);
		}
	}
}
Output:
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.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

1 comment

Leave a Reply

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