2015-10-25 12 views
3

我想實現一個通用的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的對象。

+0

我相信你HashEntry溫度應該有類型參數

+0

事實上,在SimpleHashMap所有HashEntry引用應該使用因爲HashEntry不是SimpleHashMap的內部類 –

回答

2

您需要使用類型來聲明你的臨時變量是這樣的:

HashEntry<K,V> temp = table[keyIndex]; 

的GET方法可以更新如下:

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; 
     } 

     } 
1
HashEntry temp = table[keyIndex]; 

HashEntry是一個泛型類型,但你使用它沒有類型信息。

如果你想這樣使用它,你必須使HashEntry成爲一個非泛型的內部類,並重新使用外部類的類型邊界。

public class HashEntry{ // has to be inside SimpleHashMap 
    public K key; // <-- type variables from 
    public V value; // <-- SimpleHashMap 
    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; 
    } 
} 

另一種可能是離開HashEntry,因爲它是和行更改爲

HashEntry<K, V> temp = table[keyIndex];