Using a Set (or HashSet)

Last modified: April 1, 2014 Published: March 31, 2008 by NiclasLeave a reply

This example shows how to create a Set and add objects to it. Unlike classes implementing the List interface, a Set class doesn’t allow the same value to be stored twice.
That means that using the equals method for two values, a.equals(b), cannot return true.
This is shown below where we create a HashSet object and add values to it by using the add() method. The add() method returns a boolean that tells whether the object was successfully added or not.
Later we try to add one of the values again which will make the add() method return false. The same will happen when we try to add a null value twice. The first call is ok but the second fails.