![]() | Chapter 12 | ![]() |
Set
A Set
is a collection that cannot contain duplicate elements. There are three main implementations of the Set
interface:
HashSet
, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration;TreeSet
, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet;LinkedHashSet
, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).
The main methods of any set are:
add
- adds an element to the set if it is not already present;contains
- checks if the element is present in the set.
Set<String> myMails = new HashSet<>(); myMails.add( "example@example.com" ); myMails.add( "java-is-awesome@example.com" ); myMails.add( "example@example.com" ); // the address won't be added; it is present in the set for (String address : myMails) { System.out.println(address); } List<String> names = Arrays.asList( "Anna" , "John" , "Aivar" , "Marina" , "Aivar" ); // get a set with unique elements Set<String> uniqueNames = new HashSet<>(names); // convert the set into a list names = new ArrayList<>(uniqueNames); |
Usually sets are used to get a collection of unique elements or to find the intersection, the union ja the difference (theory of sets ).
![]() | Chapter 12 | ![]() |