Using a Set (or HashSet)
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 illustrated 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. |
import java.util.HashSet; import java.util.Set; /** * * @author javadb.com */ public class Main { /** * Example method for using a Set */ public void hashSetExample() { Set vehicles = new HashSet(); //Declare some string items String item_1 = "Car"; String item_2 = "Bicycle"; String item_3 = "Tractor"; boolean result; //Add the items to the Set result = vehicles.add(item_1); System.out.println(item_1 + ": " + result); vehicles.add(item_2); System.out.println(item_2 + ": " + result); vehicles.add(item_3); System.out.println(item_3 + ": " + result); //Now we try to add item_1 again result = vehicles.add(item_1); System.out.println(item_1 + ": " + result); //Adding null result = vehicles.add(null); System.out.println("null: " + result); //Adding null again result = vehicles.add(null); System.out.println("null: " + result); } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().hashSetExample(); } } |
The output from the code is: Car: true Bicycle: true Tractor: true Car: false null: true null: false |
Search for code examples on this site
