Using a Set (or HashSet)
import java.util.HashSet;
import java.util.Set;
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);
result = vehicles.add(item_2);
System.out.println(item_2 + ": " + result);
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
0 comments: