Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into hashmap, accounting for duplicates in Set?

Tags:

java

hashmap

set

So to my knowledge duplicates are not allowed in a Java set. Why then in this code snippet does the code seem to try to take account of duplicates?

public static Subarray findSmallestSubarrayCoveringSet(List<String> paragraph,Set<String> keywords) {

   Map<String, Integer> keywordsToCover = new HashMap<>();
   for (String keyword : keywords) {
      keywordsToCover.put(keyword,
      keywordsToCover.containsKey(keyword)? keywordsToCover.get(keyword) + 1: 1);
   }

Why not just have keywordsToCover.put(keyword,1) inside the for loop?

like image 368
Matt Avatar asked Oct 29 '17 19:10

Matt


Video Answer


1 Answers

You're correct here, the call keywordsToCover.containsKey(keyword) would never be true. It just seems that whoever wrote the code didn't understand what is the purpose of a Set or they have mistakenly done so (though that's unlikely). thus just the call keywordsToCover.put(keyword,1) would suffice.

like image 94
Ousmane D. Avatar answered Oct 01 '22 08:10

Ousmane D.