Java Generic HashMap实现:对象无法转换V

我正在尝试实现一个通用的HashMap,但由于某种原因,java编译器不允许我返回正确的generics类型。

这是我的HashMap代码:

public class SimpleHashMap { 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(key, value); } else{ table[keyIndex] = new HashEntry(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{ 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 temp = table[keyIndex]; 

您的get方法可以更新如下:

 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; } return temp.value; } } 
  HashEntry temp = table[keyIndex]; 

HashEntry是一种generics类型,但您在没有类型信息的情况下使用它。

如果要像这样使用它,则必须使HashEntry成为非generics内部类并重用外部类类型边界。

 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 temp = table[keyIndex];