For example, if you want to "randomly select from a list of something and put the already selected items in the Set", It seems quite likely that "if the selected item is not in the Set, it will be added, and if it is, the error message will be processed". This is intuitive
Add if not, error if
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 10; i++){
int r = (int)(Math.random() * 10);
if (!set.contains(r)) {
set.add(r);
} else {
System.out.println(r + "Is already in");
}
}
In this way, I want to write that I should check with contains before putting it in. However, you can actually write it like this.
Error if not added
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 10; i++){
int r = (int)(Math.random() * 10);
if (!set.add(r)) {
System.out.println(r + "Is already in");
}
}
You can add it suddenly and put it in the if without checking in advance whether it is included.
Actually, I don't see much light, but add of Collection interface including Set The method returns boolean. Looking at the contents,
Guarantee that the specified element is stored in this collection (optional operation). Returns true if the collection has changed as a result of this call. This collection does not allow duplicate elements and returns false if the specified element is already included.
add is not an "add" method, but a "guarantee that the element is present" method, and returns the result of whether the collection has changed before or after it. In the case of Set, if the element to be inserted already exists, it is not added. That is, Set is never changed, so it returns false. This can be used as it is to judge "whether or not it was included". At the same time, if it does not exist, the addition has already been completed, so there is no need to rewrite the process to be added to "if it does not exist".
The code must be difficult to read intuitively. Is there a scene other than Set that can take advantage of the properties of Collection # add ...?
Recommended Posts