Java通用HashMap实现:对象不能转换V [英] Java Generic HashMap implementation: Object cannot be converted V
本文介绍了Java通用HashMap实现:对象不能转换V的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图实现一个通用的HashMap,但由于某种原因,java编译器不会允许我返回正确的泛型类型。
I'm trying to implement a generic HashMap, but for some reason the java compiler will not allow me to return the proper generic type.
这里是我的HashMap代码:
Here is my HashMap code:
public class SimpleHashMap<K,V> {
private int tableSize;
private HashEntry[] table;
public SimpleHashMap(){
table = new HashEntry[tableSize];
for(int i = 0; i < table.length; i++){
table[i] = null;
}
}
public V put(K key, V value){
int keyIndex = getHashCode(key);
if(table[keyIndex] == null){
table[keyIndex] = new HashEntry<K, V>(key, value);
}
else{
table[keyIndex] = new HashEntry<K, V>(key, value, table[keyIndex]);
}
return value;
}
public V get(K key){
int keyIndex = getHashCode(key);
if(table[keyIndex] == null){
return null;
}
else{
HashEntry temp = table[keyIndex];
while(temp != null){
if(temp.key.equals(key)){
return temp.value;
}
temp = temp.next;
}
}
}
public int getHashCode(K key){
return key.hashCode() % tableSize;
}
}
这是我的HashEntry代码:
Here is my HashEntry code:
public class HashEntry<K,V>{
public K key;
public V value;
public HashEntry next;
public HashEntry(K key, V value){
this(key, value, null);
}
public HashEntry(K key, V value, HashEntry next){
this.key = key;
this.value = value;
this.next = next;
}
}
我在编译时得到的唯一错误是: / p>
The only error I get at compile time is:
error: incompatible types: Object cannot be converted to V
return temp.value;
^
where V is a type-variable:
V extends Object declared in class SimpleHashMap
我已经尝试显式地转换它,但它仍然拒绝返回类型V的对象。
I've tried explicitly casting it, but it still refuses to return a object of type V.
推荐答案
p>您需要使用类型声明您的临时变量,如下所示:
You need to declare your temp variable with type like this:
HashEntry<K,V> temp = table[keyIndex];
您的get方法可以更新如下:
Your get method can be updated as follows:
public V get(K key){
int keyIndex = getHashCode(key);
if(table[keyIndex] == null){
return null;
}
else{
HashEntry<K,V> temp = table[keyIndex];
while(temp != null){
if(temp.key.equals(key)){
return temp.value;
}
temp = temp.next;
}
return temp.value;
}
}
这篇关于Java通用HashMap实现:对象不能转换V的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文