[英]Incompatible types when returning a generic
我正在嘗試用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
是Error:(47, 45) java: incompatible types: java.lang.Object cannot be converted to V
Entry
具有類型參數,但是您還具有一個Entry
數組。 兩者不在一起。 您有多種選擇,包括:
Entry
刪除類型參數,並使用不安全的強制類型轉換。 List
。 Entry
對象,並使用帶有Object[]
數組和不安全類型轉換的探測算法。 buckets
。 我已經在第1行及以下修改了您的getValue方法簽名,對我來說很好用。 還在第3行中使用入口值初始化添加了泛型。
雖然是第2行代碼,但散列初始化我發現效果很差,但是除非我們看到您的put(K key,V value)方法,否則無法進行過多注釋。
public <K> V getValue(K key){ // line 1
int hash = key.hashCode()%buckets.length-1; // line 2
Entry<K, V> currentEntry = buckets[hash]; //line 3
while (currentEntry!=null)
{
if (currentEntry.getKey().equals(key)){
return currentEntry.getValue();
}
currentEntry = currentEntry.next;
}
return null;
}
您需要在聲明中添加泛型:
Entry<K,V> currentEntry = buckets[hash];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.