我想實現一個通用的HashMap,但由於某種原因,java編譯器不會允許我返回適當的泛型類型。Java通用HashMap實現:對象無法轉換V
這裏是我的HashMap代碼:
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代碼:
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;
}
}
我在編譯的時候得到的唯一錯誤是:
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的對象。
我相信你HashEntry溫度應該有類型參數 –
事實上,在SimpleHashMap所有HashEntry引用應該使用因爲HashEntry不是SimpleHashMap的內部類 –