Set

The Set is a special collection that cannot contain duplicate elements. When you want to add an object into a set that already has an object that is the same or equal to the actual one, then the add method will not add the actual object. The add method will return false indicating the failure.

You can use Set in your program when you need a collection of unique elements where you simply want to check that an element is a member of a set or not, whether an object belongs to a certain group or not.

As we will return to our program code, we will see that the UniqueGuesser class has to implement an algorithm that checks that a color in a guess is present only once. This algorithm is the ideal candidate for a Set to be used:

private boolean isNotUniqueWithSet(Color[] guess) { 
final Set<Color> alreadyPresent = new HashSet<>();
for (Color color : guess) {
if (alreadyPresent.contains(color)) {
return true;
}
alreadyPresent.add(color);
}
return false;
}

The code creates a set, which is empty when the method starts. After that, it checks for each color (notice the enhanced for loop over the array elements) if it was already present before. To do that, the code checks if the color is already in the set. If it is there, the guess is not unique as we have found a color that is present at least twice. If the color was not in the set, then the guess can still be unique in colors. To be able to detect that later, the code puts the color into the set.

The actual implementation of Set that we will use is HashSet. In the JDK, there are many classes implementing the Set interface. The most widely used is HashSet, and it is also worth mentioning EnumSet, LinkedHashSet, and TreeSet. The last one also implements the SortedSet interface, so we will detail it there.

To understand what HashSet (and later HashMap) are and how they work, we will have to discuss what hashes are. They play very important and central role in many applications. They do their job under the hood in the JDK but there are some very important constraints that programmers have to follow or else really weird and extremely hard to find bugs will make their life miserable. I dare to say that violation of the hash contract in HashSet and HashMap are the cause of the second most difficult to find bugs next to multithread issues.

Thus, before going on with the different collection implementations, we will visit this topic. We are already one level deep from our example in this detour discussing collections and now we will go one level deeper. I promise this is the last in-depth level of detours.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.36