Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap and int as key

Tags:

java

hashmap

I am trying to build a HashMap which will have integer as keys and objects as values.

My syntax is:

HashMap<int, myObject> myMap = new HashMap<int, myObject>(); 

However, the error returned is - Syntax error on token "int", Dimensions expected after this token - I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

What could I do?

Thanks in advance! :)

like image 565
MrD Avatar asked Apr 22 '13 13:04

MrD


People also ask

Can I use int as key in HashMap?

HashMap doesn't handle primitives, just objects. Related SO question, but with int being the value, not the key.

Can int be a key?

These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.

Can a HashMap be a key?

Yes, a HashMap can be used as a key to another map, as the class properly overrides .

Can a HashMap have an array as a key?

You cannot do it this way. Both t and a will have different hashCode() values because the the java. lang. Array.


1 Answers

Use Integer instead.

HashMap<Integer, MyObject> myMap = new HashMap<Integer, MyObject>(); 

Java will automatically autobox your int primitive values to Integer objects.

Read more about autoboxing from Oracle Java documentations.

like image 169
gaborsch Avatar answered Oct 11 '22 09:10

gaborsch