9. 19. 1. Set and HashSet |
|
- A Set represents a mathematical set.
- It is a Collection that, unlike List, does not allow duplicates.
- There must not be two elements of a Set, say e1 and e2, such that e1.equals(e2).
- The add method of Set returns false if you try to add a duplicate element.
|
import java.util.HashSet;
import java.util.Set;
public class MainClass {
public static void main(String[] a) {
Set set = new HashSet();
set.add("Hello");
if (set.add("Hello")) {
System.out.println("addition successful");
} else {
System.out.println("addition failed");
}
}
}
|
|
addition failed |
- HashSet allows at most one null element.
- HashSet is faster than other implementations of Set, TreeSet and LinkedHashSet.
|