A set is a kind of Collection that models the mathematical set abstractions. It is an non-ordered collection of objects that can not store duplicate values. So, it means that a set can contain an element only once. The set interface contains methods inherited from Collection.

Java contains three general-general purpose set implementations HashSet, LinkedHashSet, and TreeSet. HashSet is the best-performing implementation which stores it’s elements in a hash table. TreeSet is slower than HashSet because it stores it's elements in a red-black tree and orders it's elements based on their values.

java.util.set represents a collection of objects where each object in the set is unique. You can add a Java object to a set.

A simple Java Set example:

Set setA = new HashSet();
String element = "element 0";

Here, in this example, the program creates a Hashset. Then it adds a string object to the set, and then checks if the set contains the added element.

Characteristics Of Java Set

  • The elements in a Set are not stored in order. It means you will not find elements sorted in an order while iterating over elements of a Set.
  • Unlike List, Set cannot store duplicate elements
  • Unlike List and arrays, Set doesn’t support indexes or positions of the elements.
  • Set allows you to add at most one null element only.
  • Set supports Generics. Using Generics with Set will let you avoid ClassCastException at runtime

List Vs Set

The Java List and Java Set interfaces both represent a collection of elements. But there are some differences in the methods which List and Set interfaces offer.

One difference between Java List and Java Set interface is that the same element can occur more than once in a Java List but in Java Set each element can occur only once.

Another difference is that the elements in a List has an order which can be iterated in that order. But, the Java Set doesn’t have any particular order of elements for iteration.

When To Use Set

Both Set and List are interface. If you want to use features of Set interface then you have to use the classes like HashSet, TreeSet, LinkedHashSet. And, if you want to use features of List interface then you have to use classes like ArrayList, LinkedList, etc.

If you have the requirement of duplicating elements then go for List interface and if your task doesn’t need duplicate values then go for Set interface. But, after selecting the interface you have to use appropriate implemented class for better performance and memory usage.

For example, if you choose Set interface and you don’t want to maintain the order then you can go for HashSet.

A List is automatically ordered but a Set is only ordered depending on how you implement it. If you are working with numbers, a List may be easier as it is already ordered.

In short, use Set for storing unique objects in random order and use List for storing non-unique objects as per insertion order.

UseFul Methods Used in Java Set

  • add() : Adds an object to the collection.
  • clear() : Removes all the objects from the collection.
  • contains() : Returns true if a specified object is an element within the collection.
  • size() : Returns the number of elements in the collection.
  • remove() : Removes a specified object from the collection.
  • isEmpty() : Return true if the collection has no elements.
  • Iterator() : Return an iterator object for the collection.
  • Object[] toArray() : Returns an array containing all of the elements in this set.

Set Implementations

Adding element to Set:

Set setA = new HashSet();

Iterating elements of Set:

There are two ways to iterate elements of a Java Set Using an Iterator obtained from the Set

Iterator iterator = set.iterator();
	String element = (String);

Using the for-each loop

for(Object object : set){
	String element = (String) object:

Removing elements:

You can remove elements from a Set by calling remove(Object o) method.

set.remove("Object to remove");

Removing all elements:


Example Of Java Set:

import java.util.*;
public class SetDemo {
  public static void main(String args[]) { 
      int count[] = {57,24,89,13,45,19};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      catch(Exception e) {}

The output is:
The sorted list is :
The first element of the set is: 13
The last element of the set is: 89


EnumSet is a specialized set implementation for use with enum types. It is a member of the Java Collection Framework which is not synchronized. It inherits AbstractSet class.

All the elements in an enum set must come from a single enum type, when the set is created. Enum sets are represented as bit vectors internally which is extremely compact and efficient.

As EnumSet is not synchronized, then if multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally.


public abstract class EnumSet<E extends Enum<E>>

Here, E specifies the elements and must extend Enum. This imposes the requirement that the elements must be of specified enum type.


import java.util.EnumSet;

enum Abc
public class Example
	public static void main(String[] args)
		// Creating a set
		EnumSet<Abc> set1, set2, set3, set4;

		// Adding elements
		set1 = EnumSet.of(Abc.QUIZ, Abc.CONTRIBUTE,
		Abc.LEARN, Abc.CODE);
		set2 = EnumSet.complementOf(set1);
		set3 = EnumSet.allOf(Abc.class);
		set4 = EnumSet.range(Abc.CODE, Abc.CONTRIBUTE);
		System.out.println("Set 1: " + set1);
		System.out.println("Set 2: " + set2);
		System.out.println("Set 3: " + set3);
		System.out.println("Set 4: " + set4);


Set 2: [MCQ]

Methods in EnumSet:

  • static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) It is used to create an enum set containing all of the elements in the specified element type.
  • EnumSet<E> Clone() This method returns a copy of this set.
  • static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) It is used to create an empty enum set with the specified element type.
  • static <E extends Enum<E>> EnumSet<E> of(E e) It is used to create an enum set initially containing the specified element.
  • static <E extends Enum<E>> EnumSet<E> range(E from, E to) It is used to create an enum set initially containing the specified elements.


HashSet is used to create a collection backed by a hash table for storage. HashSet stores the elements by using a mechanism known as hashing.

HashSet class offers constant time performance for the basic operations like add, remove, contains and size assuming the hash function breaks down the elements properly among the buckets.

Characteristics Of HashSet:

  • HashSet contains unique elements only
  • Null elements are allowed in HashSet
  • HashSet implements Searlizable and Cloneable interfaces.
  • Objects that are inserted in HashSet are not guaranteed to be in the same order. It totally depends on their Hash code.
  • HashSet supports Generics, this is the recommended approach to avoid ClassCastException at runtime.
  • HashSet uses HashMap for storing elements.


public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable


import java.util.*;  
class NewOne{  
 public static void main(String args[]){  
  //Creating HashSet and adding elements  
  HashSet<String> set=new HashSet<String>();  
  //Traversing elements  
  Iterator<String> itr=set.iterator();  



Methods in HashSet:

  • boolean add(E e): The specified element is added if it is not present, if it is present then return false.
  • Void clear(): Removes all the elements from set.
  • Int size(): Returns the size of the set.
  • Object clone(): Creates a shallow copy of the set.
  • Boolean isEmpty: Checks whether the set is empty or not. Return true for empty and false for non-empty.
  • Iterator iterator(): Returns an iterator over the element in the set
  • Boolean contains(Object o): Return true if an element is present in set.
  • HashSet(): Used to create a default HashSet.
  • HashSet(Collection c): Used to initialize the HashSet by using the elements of the collection c


LinkedHashSet is a Hash table and an ordered version of HashSet that maintains doubly-linked List across all elements. It inherits HashSet class and implements Set interface.

When iteration order is needed to be maintained LinkedHashSet class is used. It allows us iterate through the elements in the order in which they were inserted.

Characteristics Of LinkedHashSet:

  • LinkedHashSet contains unique elements just like HashSet.
  • It permits null elements.
  • It provides all optional set operations.
  • It maintains insertion order.
  • A LinkedHashSet has two parameters that affect it’s performance: initial capacity and load factor.


	public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable  


import java.util.*;  
class TestCollection10{  
 public static void main(String args[]){  
  LinkedHashSet<String> al=new LinkedHashSet<String>();  
  Iterator<String> itr=al.iterator();  



Constructors in LinkedHashSet :

  • LinkedHashSet(int i): Used initialize the capacity of the linkedhashset to the given integer value capacity.
  • LinkedHashSet(int i, float f): Used to initialize both i and f of the Hash Set from it’s argument.


TreeSet is one of the most important implementation which implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface.

The ordering of the elements is maintained by a set using their natural ordering. It is also also ordered by a Comparator provided at set creation time.

Characteristics Of TreeSet:

  • It contains unique elements just like TreeSet.
  • It maintains ascending order.
  • The access and retrieval times are quiet fast.
  • TreeSet can be used to store large amount of sorted information which are supposed to be accessed quickly.
  • TreeSet does not allow to insert Heterogeneous objects.
  • TreeSet doesn’t allow duplicate values by implementing SortedSet interface.


public class TreeSet<E> extends AbstractSet<E> 
	implements NavigableSet<E>, Cloneable, Serializable


import java.util.*;  
class TestCollection11{  
 public static void main(String args[]){  
  //Creating and adding elements  
  TreeSet<String> al=new TreeSet<String>();  
  //Traversing elements  
  Iterator<String> itr=al.iterator();  



Methods in TreeSet:

  • void clear(): Removes all of the elements from the set.
  • void add(Object o): Used to add specified element to the set if it is not already present.
  • Object clone(): Returns a shallow copy of TreeSet instance.
  • Object first(): Returns the lowest element currently in the sorted set.
  • Object last(): Returns highest element currently in the sorted list.
  • boolean isEmpty(): Return true if the set contains no elements.
  • boolean addAll(Collection c): Adds all of the elements in the specified collection to the set.
  • boolean remove(Object o): Removes the specified element from the set if it is present.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to for any queries

If you already registered then please do check your email for the Webex link