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

Answer:

If we insert duplicate values to the Set , we don’t get any compile time or run time errors. 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.

 

Output:
Colours available in set are:
Blue
Red
Green