If we try to insert duplicate values in a “Set”, what will happen? Do we get any complier error?

Just it doesn’t add duplicate values. Boolean add(E e) – Adds the specified element to this set if it is not already present (optional operation). As, add() method returns Boolean and on adding duplicates it will return false. Below java source code example works fine and JVM (Java Virtual Machine) doesn’t complain.

If we insert duplicate values to the Set, we don’t get any compile time or run time errors. It doesn’t add duplicate values in the set.

Below is the add() method of the set interface in java collection that returns Boolean value either TRUE or FALSE when the object is already present in the set.

[ Boolean add(E e) – Adds the specified element to this set if it is not already present . RETURNS:  Boolean value true/false.]

Simple program to demonstrate, what happens if you add duplicate elements to a set.

We have created a set to store different types of colours by using Set interface reference with Hashset class object. We are adding different types of colours e.g. Red, Green and Blue etc. in the set and displaying the colours on console screen by iterating the set in for loop.

Intentionally, we have added a Blue color again to check hashset duplicates acceptance. Notice that the java program will work fine and does not throw any compiler or run time error. But, it will not store duplicate values.

Source code example: To check if java set add same element or not

import java.util.HashSet;
import java.util.Set;

public class CanAddDuplicateValueInSet {	
	
	public static void main(String[] args) {
		
		Set uniqueColours = new HashSet();
		
		uniqueColours.add("Red");
		uniqueColours.add("Green");
		uniqueColours.add("Blue");
		uniqueColours.add("Blue"); /*Adding duplicate value here, 
		No compiler error and code works fine but doesn't add duplicate value */
		
		System.out.println("Colours available in set are:");
		for (String c : uniqueColours){
			
			System.out.println(c);
		}	
	}
}

Output:
Colours available in set are:
Blue
Red
Green

Quick refreshment Questions and Answers on java set add duplicate.

  • Q) Can hashset have duplicate values?
    • A) No, hashset cannot have duplicate values.
  • Q) What does hashset return when the object is already present? false true null object
    • A) A Boolean value is returned by its add () method i.e. TRUE in object is not present and false if already present in the set.
  • Q) What happens if you add duplicate elements to a set?
    • A) Program will not show any compiler error or run time error and it will not allow duplicates.

Related Posts