HashMap和int作为键 [英] HashMap and int as key

查看:104
本文介绍了HashMap和int作为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的语法是:

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

但是,返回的错误是 - 标记int的语法错误,我不明白为什么我应该添加一个维度(即:将int作为数组),因为我只需要将数字作为关键字存储。



我能做些什么是吗?



预先感谢! :)

解决方案

不能使用原语,因为HashMap在内部使用对象作为键。所以你只能使用从Object继承的对象(即任何对象)。

这是函数put()在HashMap中,正如你可以看到它使用Object对于K:

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

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

表达式k = e.key应该清楚。 p>

我建议使用像Integer和自动装箱这样的包装。


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.

这篇关于HashMap和int作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆