Java 通用 HashMap 实现 : Object cannot be converted V

标签 java generics casting hashmap

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

这是我的 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<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;
        }

      }

关于Java 通用 HashMap 实现 : Object cannot be converted V,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328133/

相关文章:

java - 无法为 IntelliJ Idea 设置 SDK

java - 测试 Java 正则表达式appendReplacement()

java - 无法编译使用通用列表参数调用接口(interface)中方法的类

c# - 通用类和静态字段

c++ - 从指向基对象的指针初始化派生对象

java - 膨胀类 com.google.android.material.tabs.TabLayout 时出错 - Android 问题

java - 使用guava将集合映射到id

java - 使用 typeliteral 在 guice 中注入(inject)泛型,但 typeliteral 构造函数受到保护

postgresql - 我无法修复这个看似简单的与转换相关的 postgresql 错误

class - 通过反射将类强制转换为基接口(interface)导致异常