Java Tutorials
Java Methods
Java Classes
Java File Handling
HashSet is a collection of items where everything is different, and is available in the java.util
package:
Create a HashSet
object called cars that will store strings:
import java.util.HashSet; // Import the HashSet class
HashSet<String> cars = new HashSet<String>();
The HashSet
section has many useful features. For example, to add items to it, use the add()
method:
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
}
}
Note: In the example above, although the BMW has been added twice it appears only once in the set because everything in the set must be different.
To check an item in HashSet, use the method contains()
:
cars.contains("Mazda");
To remove an item, use the remove()
method:
cars.remove("Volvo");
To delete all items, use the clear()
method:
cars.clear();
To find out how many items there are, use the size
method:
cars.size();
Check the HashSet
items for-each loop:
for (String i : cars) {
System.out.println(i);
}
The items in the HashSet are actually objects. In the examples above, we created "String" type objects. Remember that String in Java is an object (not an old version). To use other types, such as int, you must specify an equal wrapper category: Integer
. For other classic types, use: Boolean
boolean, Character
for Character, Double
for double, etc:
Use a HashSet
that stores Integer
objects:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet<Integer> numbers = new HashSet<Integer>();
// Add values to the set
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Show which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found in the set.");
} else {
System.out.println(i + " was not found in the set.");
}
}
}
}