-2

What assumptions do I need to make on my input before using HashMap? Besides assuming that it should be an even distribution? Is there some sort of input that I can't use with HashMap?

Thanks

Update - Got my answer:)

marinaaa
  • 21
  • 3
  • 3
    I am not quite sure I understand what you mean. It is a map. It maps keys to values. You cannot use primitives, obviously. You do not need an equal distribution of keys, although performance is better if your keys (i.e. their hash codes) are evenly distributed. You should keep in mind that there is a contract between [`Object#equals(...)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)) and [`Object#hashCode()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#hashCode()) – Turing85 Feb 17 '19 at 21:59
  • You need to understand how hash code is computed for your input since HashMap calculates the 'slot' of the value based on the result of hashCode. If you want to get the best performance out of HashMap you need to make sure the value of hashcode() is 1) diverse enough in values 2) evenly distributed across all input values. – seiya Feb 17 '19 at 22:06
  • You need to read the Javadoc. The requirements for keys are clearly stated. – user207421 Feb 17 '19 at 22:15
  • The key objects should implement efficient and stable `hashCode()` + (and values also:)`equals()` methods ... you cannot use 'primitive types'...even distribution?? no requirements/assumptions on that. – xerx593 Feb 17 '19 at 22:50
  • @Turing85 thank you I got it. – marinaaa Feb 17 '19 at 22:53

1 Answers1

0

Your input obviously should match type of the HashMap. HashMap<String, Object> here String is type of the key and Object is type of the value.

You can't use primitive types with hashmap like HashMap<int, double> There are wrappers for all primitive types: HashMap<Integer, Double>.

Also you can add null key and value.

See also:

Understanding the workings of equals and hashCode in a HashMap

HashMap with Null Key and Null Value

Why don't Java Generics support primitive types?

Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • It is worth mentioning that the wrappers are objects and thus some time will be lost in order to construct/fetch/garbage-collect those object. This is one reason why one goal of [Project Valhalla](https://openjdk.java.net/projects/valhalla/) is ot allow primitives and value types as generic parameters. – Turing85 Feb 17 '19 at 22:10