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


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.


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.


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);
链接地址: http://www.djcxy.com/p/59500.html

上一篇: 如果块变量定义给出错误,则使用大括号

下一篇: HashMap和int作为键