6

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?

2

2 Answers 2

1

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.

0

You are correct, as it says in the Javadoc:

a Set is a collection that contains no duplicate elements.

Who ever wrote that sample is unaware of this fact.

There will never be a case where keywordsToCover.containsKey(keyword) returns true, unless keywordsToCover is initialized (outside of the method) as static and is not reconstructed every time findSmallestSubarrayCoveringSet is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.