我试图在Java中实现HashMap,但在尝试返回值时出现此错误。这是Entry
类:返回通用类型时不兼容的类型
public class Entry<K,V> {
private K key;
private V value;
public Entry next;
public Entry(K key, V value)
{
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
这是我想回到什么:
private Entry[] buckets = new Entry[255];
public V getValue(K key){
int hash = key.hashCode()%buckets.length-1;
Entry currentEntry = buckets[hash];
while (currentEntry!=null)
{
if (currentEntry.getKey().equals(key)){
return currentEntry.getValue(); //error here
}
currentEntry = currentEntry.next;
}
return null;
}
我得到的错误是Error:(47, 45) java: incompatible types: java.lang.Object cannot be converted to V
我怀疑'Entry currentEntry'应该是'Entry currentEntry';也用'桶'。 –
...并且按原样,此代码应该发出“未经检查”的警告。 – dhke
并且'int hash = key.hashCode()%buckets.length-1'也有问题,因为它可以返回值为'-1'的值,这会在以下语句中引发异常。 –