'HashMap and int as key
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! :)
Solution 1:[1]
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 2:[2]
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 3:[3]
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 4:[4]
You may try to use Trove http://trove.starlight-systems.com/
TIntObjectHashMap is probably what you are looking for.
Solution 5:[5]
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:[6]
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:[7]
If you code in Android, there is SparseArray, mapping integer to object.
Solution 8:[8]
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:[9]
use int as Object not as primitive type
HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();
Solution 10:[10]
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:[11]
Please use
HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();
Solution 12:[12]
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:[13]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow