Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
EnumSet in Java
Next article icon

AbstractSet Class in Java

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the AbstractSet class is part of the Java Collections Framework. It provides a Skeleton implementation of the set interface, which is a collection that does not allow duplicate elements. This class is abstract, meaning it cannot be instantiated directly, but it can be extended to create a custom set implementation

  • AbstractSet implements the set interface but does not provide a full implementation of all set methods.
  • It provides implementations for methods like size(), isEmpty() and contains()
  • It requires subclasses to implement the iterator()method to define how elements are iterated over

Example: This example demonstrates how to insert elements into a set and print them.

Java
// Java Program to demonstrates the  // working of AbstractSet class import java.util.HashSet; import java.util.Set;  abstract class AbstractSet {          // Abstract method to insert an element     public abstract void insert(int element);      // Abstract method to display the elements     public abstract void display(); }  class MySet extends AbstractSet {          // Set to hold the elements     private Set<Integer> elements;      // Constructor     public MySet() {         elements = new HashSet<>();     }      // Implement the insert method     public void insert(int element) {         elements.add(element);     }      // Implement the display method     public void display() {         for (Integer element : elements) {             System.out.println(element);         }     } }  public class Geeks {     public static void main(String[] args) {         MySet s = new MySet();                  // Insert elements         s.insert(10);         s.insert(20);         s.insert(30);                  // Display elements         System.out.println("Elements in the set:");         s.display();     } } 

Output
Elements in the set: 20 10 30 

AbstractSet Class Hierarchy

From the below diagram, it can be concluded that it implements Iterable<E>, Collection<E>, Set<E> interfaces. The direct subclasses are CopyOnWriteArraySet, EnumSet, HashSet, TreeSet.

AbstractSet-Class-in-Java

Declaration of AbstractSet Class

In Java, the declaration of AbstractSet Class can be done as:

public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E>

Constructor

Constructor

Description

 protected AbstractSet()

This Constructor is used to prevent direct instantiation of the AbstractSet class, allowing only its subclasses to be instantiated.


Example: This example demonstrates how a protected constructor in an abstract class can only be called by its subclasses, and how the subclass must implement abstract methods from the abstract class.

Java
// Java program demonstrating the  // working of a protected constructor  // in an abstract class  // Abstract class with a protected constructor abstract class AbstractSet {          // Protected constructor, cannot be      // called directly from outside the class     protected AbstractSet() {         System.out.println("AbstractSet constructor called");     }      // Abstract method to be implemented by subclasses     public abstract void display(); }  // Concrete subclass extending AbstractSet class MySet extends AbstractSet {          // Constructor for MySet     public MySet() {                  // Calls the protected constructor of AbstractSet         super();         System.out.println("MySet constructor called");     }      // Implementation of the abstract display method     @Override     public void display() {         System.out.println("Displaying elements in MySet");     } }  public class Geeks {     public static void main(String[] args) {         // We cannot instantiate AbstractSet directly          // because it is an abstract class         // AbstractSet set = new AbstractSet();          // This would cause a compile-time error          // Creating an instance of MySet, which is a subclass of AbstractSet         MySet set = new MySet();                  // Calling the display method of MySet         set.display();     } } 

Output
AbstractSet constructor called MySet constructor called Displaying elements in MySet 

Performing Various Operations on AbstractSet

1. Adding elements: We can use add() method to insert element to a AbstractSet class.

Example: This example demonstrates how to insert elements into an AbstractSet using a LinkedHashSet to maintain the order of insertion and display them in that order.

Java
// Java Program to Illustrate AbstractSet Class import java.util.*;  // Concrete subclass of AbstractSet public class Geeks {     public static void main(String[] args) {                  // Creating a LinkedHashSet to          // maintain insertion order         AbstractSet<Integer> set = new LinkedHashSet<>();          // Adding elements to the AbstractSet          // (through LinkedHashSet)         set.add(10);         set.add(20);         set.add(30);         set.add(40);         set.add(50);          System.out.println("AbstractSet elements: " + set);     } } 

Output
AbstractSet elements: [10, 20, 30, 40, 50] 


2. Removing Elements: We can use various methods like remove(), removeAll(), retainAll() and clear() method to remove elements from the AbstractSet.

Example: This example demonstrates how to remove a single element using remove() and multiple elements using removeAll() from a HashSet, which a concrete subclass of AbstractSet.

Java
// Java Program to demostrates  // the working of remove() and // removeAll() method import java.util.*; public class Geeks {     public static void main(String[] args)     {         // Creating a HashSet, which is a concrete subclass         // of AbstractSet         Set<Integer> set = new HashSet<>();          // Adding elements to the set         set.add(1);         set.add(2);         set.add(3);         set.add(4);         set.add(5);          // Printing the set before removal         System.out.println("Set before removal(): " + set);          // Removing a single element using remove()          // Removes the element 3 from the set         set.remove(3);         System.out.println(             "Set after removal of element 3: " + set);          // Creating a collection to remove multiple elements         List<Integer> l = new ArrayList<>();         l.add(1);         l.add(5);          // Removing all elements in the collection using         // removeAll() Removes all elements that are in l         set.removeAll(l);         System.out.println("Set after removeAll() : "                            + set);     } } 

Output
Set before removal(): [1, 2, 3, 4, 5] Set after removal of element 3: [1, 2, 4, 5] Set after removeAll() : [2, 4] 


3. Iterating Elements: We can use the iterator() method to iterate over the elements of a AbstractSet.

Example:

Java
// Java Program to demosntrates  // the working of iterator() import java.util.*; public class Geeks{     public static void main(String[] args) {                  // Creating a HashSet, which is a          // concrete subclass of AbstractSet         Set<Integer> set = new HashSet<>();                  // Adding elements to the set         set.add(1);         set.add(2);         set.add(3);         set.add(4);         set.add(5);                  // Creating an iterator to iterate over the set         Iterator<Integer> i = set.iterator();          // Iterating over the elements using the iterator         System.out.println("Iterating over the set elements:");         while (i.hasNext()) {                          System.out.print(i.next() + "  ");         }     } } 

Output
Iterating over the set elements: 1  2  3  4  5  

Methods

Methods

Description

 equals​(Object o)Compares the specified object with this set for equality.
 hashCode()Returns the hash code value for this set.
removeAll​(Collection<?> c)Removes from this set all of its elements that are contained in the specified collection (optional operation).

Methods Declared in Class java.util.AbstractCollection

Method

Description

add​(E e)Ensures that this collection contains the specified element (optional operation).
addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection to this collection (optional operation).
clear()Removes all of the elements from this collection (optional operation).
contains​(Object o)Returns true if this collection contains the specified element.
containsAll​(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements contained in this collection.
remove​(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
retainAll​(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
toArray()Returns an array containing all of the elements in this collection.
toArray​(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
 toString()Returns a string representation of this collection.

Methods Declared in Interface java.util.Collection

Method

Description

parallelStream()Returns a possibly parallel Stream with this collection as its source.
removeIf​(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
stream()Returns a sequential Stream with this collection as its source.
toArray​(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Methods Declared in interface java.lang.Iterable

Method

Description

forEach​(Consumer<? super T> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Methods Declared in interface java.util.Set

Method

Description

add​(E e)Adds the specified element to this set if it is not already present (optional operation).
addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection to this set if they’re not already present (optional operation).
clear()Removes all of the elements from this set (optional operation).
contains​(Object o)Returns true if this set contains the specified element.
containsAll​(Collection<?> c)Returns true if this set contains all of the elements of the specified collection.
isEmpty()Returns true if this set contains no elements.
iterator()Returns an iterator over the elements in this set.
remove​(Object o)Removes the specified element from this set if it is present (optional operation).
retainAll​(Collection<?> c)Retains only the elements in this set that are contained in the specified collection (optional operation).
size()Returns the number of elements in this set (its cardinality).
spliterator()Creates a Spliterator over the elements in this set.
toArray()Returns an array containing all of the elements in this set.
toArray​(T[] a)Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array

Characteristics

Some of the key characteristics of AbstractSet are listed below:

  • Implements the Set interface: AbstractSet implements the Set interface, which means that it provides a standard set of methods to manipulate sets.
  • Implements some set methods: AbstractSet implements some of the methods of the Set interface, such as size(), isEmpty(), contains(), and remove().
  • Supports iterator: AbstractSet provides an iterator method that returns an Iterator over the elements in the set.
  • Does not implement all set methods: AbstractSet is an abstract class and does not implement all the methods of the Set interface. Some of the methods that are not implemented include add(), addAll(), and clear(). These methods must be implemented by subclasses of AbstractSet.
  • Provides default implementations: AbstractSet provides default implementations for some methods of the Set interface, which can be overridden by subclasses if needed.
  • Supports null elements: AbstractSet allows null elements to be added to the set.
  • Unordered: AbstractSet is an unordered set, which means that the order in which elements are added to the set is not preserved.
  • Thread-unsafe: AbstractSet is not thread-safe, which means that if multiple threads access the same set simultaneously, it can lead to data inconsistencies. If thread safety is required, a synchronized set or a concurrent set can be used.

Next Article
EnumSet in Java

R

RishabhPrabhu
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java - util package
  • Java-AbstractSet
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    Set in Java
    The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of duplicat
    14 min read
    AbstractSet Class in Java
    In Java, the AbstractSet class is part of the Java Collections Framework. It provides a Skeleton implementation of the set interface, which is a collection that does not allow duplicate elements. This class is abstract, meaning it cannot be instantiated directly, but it can be extended to create a c
    8 min read
    EnumSet in Java
    In Java, the EnumSet is a specialized set implementation for use with enum types. It is a part of java.util package and provides a highly optimized set for storing enum constants. The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type.It extends
    9 min read
    Java HashSet
    HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon
    12 min read
    TreeSet in Java
    TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ
    13 min read
    ConcurrentSkipListSet in Java
    In Java, the ConcurrentSkipListSet is the part of the java.util.concurrent package and provides a scalable, thread-safe alternative to TreeSet. It is a sorted set that lets multiple threads safely access and modify the set at the same time without causing issues.It is thread-safe.Elements are in sor
    7 min read
    CopyOnWriteArraySet in Java
    In Java, the CopyOnWriteArraySet is the part of the java.util.concurrent package and is used to handle thread-safe operations in multi-threaded environments. It is ideal when the set is frequently read but infrequently modified. The set ensures safe access for multiple threads, as it creates a new c
    6 min read
    Java LinkedHashSet
    LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el
    8 min read
    Convert HashSet to TreeSet in Java
    Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is
    3 min read
    Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
    In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHa
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences