HashMap and int as key

JavaHashmap

Java Problem Overview


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! :)

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

For everybody who codes Java for Android devices and ends up here: use SparseArray for better performance;

private final SparseArray<myObject> myMap = new SparseArray<myObject>();

with this you can use int instead of Integer like;

int newPos = 3;

myMap.put(newPos, newObject);
myMap.get(newPos);

Solution 3 - Java

You can't use a primitive because HashMap use object internally for the key. So you can only use an object that inherits from Object (that is any object).

That is the function put() in HashMap and as you can see it uses Object for K:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

The expression "k = e.key" should make it clear.

I suggest to use a wrapper like Integer and autoboxing.

Solution 4 - Java

You may try to use Trove http://trove.starlight-systems.com/
TIntObjectHashMap is probably what you are looking for.

Solution 5 - Java

HashMap does not allow primitive data types as arguments. It can only accept objects so

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

will not work.

You have to change the declaration to

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

so even when you do the following

myMap.put(2,myObject);

The primitive data type is autoboxed to an Integer object.

8 (int) === boxing ===> 8 (Integer)

You can read more on autoboxing here http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Solution 6 - Java

The main reason with HashMap not allowing primitive as keys is that HashMap is designed in such a way that for comparing the keys, it makes use of equals() method, and a method can be called only on an object not on a primitive.

Thus when int is autoboxed to Integer, Hashmap can call equals() method on Integer object.

That is why, you should use Integer instead of int. I mean hashmap throws an error while putting int as a key (Don't know the meaning of the error that is thrown)

And if you think that, you can make Map performance faster by making a primitive as a key, there is a library called FastUtil which contains a Map implementation with int type as a key.

Because of this, it is much faster than Hashmap

Solution 7 - Java

If you code in Android, there is SparseArray, mapping integer to object.

Solution 8 - Java

For somebody who is interested in a such map because you want to reduce footprint of autoboxing in Java of wrappers over primitives types, I would recommend to use Eclipse collections. Trove isn't supported anymore, and I believe it is quite unreliable library in this sense (though it is quite popular anyway) and couldn't be compared with Eclipse collections.

import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;

public class Check {
    public static void main(String[] args) {
        IntObjectHashMap map = new IntObjectHashMap();

        map.put(5,"It works");
        map.put(6,"without");
        map.put(7,"boxing!");

        System.out.println(map.get(5));
        System.out.println(map.get(6));
        System.out.println(map.get(7));
    }
}

In this example above IntObjectHashMap.

As you need int->object mapping, also consider usage of YourObjectType[] array or List<YourObjectType> and access values by index (as map is, by nature, an associative array).

Solution 9 - Java

use int as Object not as primitive type

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

Solution 10 - Java

If you are using Netty and want to use a map with primitive int type keys, you can use its IntObjectHashMap

Some of the reasons to use primitive type collections:

  • improve performance by having specialized code
  • reduce garbage that can put pressure on the GC

The question of specialized vs generalized collections can make or break programs with high throughput requirements.

Solution 11 - Java

Please use HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();

Solution 12 - Java

> 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.

An array is also an Object, so HashMap<int[], MyObject> is a valid construct that uses int arrays as keys.

Compiler doesn't know what you want or what you need, it just sees a language construct that is almost correct, and warns what's missing for it to be fully correct.

Solution 13 - Java

Just like the list doesn't take the primitive data, map doesn't take the primitive data types as key or value. if we try to put primitive data types as the key value pair it will do the autoboxing

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMrDView Question on Stackoverflow
Solution 1 - JavagaborschView Answer on Stackoverflow
Solution 2 - JavaStepoidView Answer on Stackoverflow
Solution 3 - Javauser1883212View Answer on Stackoverflow
Solution 4 - JavaArekView Answer on Stackoverflow
Solution 5 - JavaLakshmiView Answer on Stackoverflow
Solution 6 - JavaFatherMathewView Answer on Stackoverflow
Solution 7 - JavaalvinsjView Answer on Stackoverflow
Solution 8 - JavaAlexView Answer on Stackoverflow
Solution 9 - Javafranki3xeView Answer on Stackoverflow
Solution 10 - JavaEvgeniy BerezovskyView Answer on Stackoverflow
Solution 11 - JavaMichaelView Answer on Stackoverflow
Solution 12 - JavaYoory N.View Answer on Stackoverflow
Solution 13 - JavaSumanView Answer on Stackoverflow