3

So, I have a HashMap map containing ~120.000 entries. Every time a new entry comes, I check if the entry already exists in the HashMap (if(!map.containsKey(hashcode))) and if it doesn't I create a new object and put it in the HashMap.

Now my question is: Would it be better to create a boolean array NxN (with N = 6.000) and check every time if the array element in [n1][n2] is false (not in hashmap yet) or true (the pair is in HashMap), instead of using the .containsKey()?

2
  • Are you actually using the hashcode as they key? That wouldn't be necessary because then internally the HashMap will create a hashcode from the hashcode. Commented May 22, 2019 at 15:20
  • In what way "better"? Commented May 22, 2019 at 16:24

3 Answers 3

2

Map has computeIfAbsent() method which does exactly what you need:

  • If the specified key is not already associated with a value (or is mapped
  • to {@code null}), attempts to compute its value using the given mapping
  • function and enters it into this map unless {@code null}. *
  • If the function returns {@code null} no mapping is recorded. If

  • the function itself throws an (unchecked) exception, the
  • exception is rethrown, and no mapping is recorded. The most
  • common usage is to construct a new object serving as an initial
  • mapped value or memoized result

Regarding option with array, if your hashing algorithm for keys is good then your map will execute lookups by key in approximately O(1) which is as good as lookup in array by index. But your additional array will use additional memory and is not needed in this case.

Sign up to request clarification or add additional context in comments.

2 Comments

What's the time complexity of computeIfAbsent method? Is it fair to say that its O(1)?
@theprogrammer if actual compute algorithm (how you calculate new value) doesn't touch existing map then yes, it is O(1)
0

See, HashMap is having Time Complexity of O(1), so getting checked by containsKey is best solution in your case.

Comments

0

Nope, containsKey is a perfectly fine way. HashMaps have a usual lookups of O(1), so it should not be an issue, unless the objects being stored have a poorly implemented hash algorithm. Only question could be, why do you have so many entries in a HashMap?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.