使用泛型创建哈希表遇unexpected type错误,求解决方法
解决Java泛型错误:
java: unexpected type required: class found: type parameter K 错误原因
Java泛型存在类型擦除机制,编译后泛型参数K、V的具体类型信息会被擦除,JVM无法在运行时确定要实例化的具体类,因此不能直接使用new K(key)或new V(value)这种语法。而且你的场景里完全没必要这么做——key本身就是K类型的实例,value本身就是V类型的实例,直接赋值即可。
代码修正及问题说明
以下是修正后的完整代码,同时修复了其他潜在问题:
import java.util.List; import java.util.Vector; import java.util.ArrayList; class HashT<K, V> { int tsize; Vector<List<Object[]>> table; public HashT(int tsize) { // 修正构造函数赋值错误:把局部变量赋值给成员变量 this.tsize = tsize; this.table = new Vector<>(tsize); // 初始化每个位置的List,避免NullPointerException for (int i = 0; i < tsize; i++) { this.table.add(new ArrayList<>()); } } private int hashfn(K x) { // 用hashCode实现通用哈希函数,处理负数哈希值确保非负 return (x.hashCode() & 0x7FFFFFFF) % this.tsize; } public void insert(K key, V value) { int hashIndex = hashfn(key); List<Object[]> l = this.table.elementAt(hashIndex); // 初始化数组,长度为2 Object[] tpl = new Object[2]; // 直接赋值已有实例,无需new K/V tpl[0] = key; tpl[1] = value; l.add(tpl); } public V get(K key) { int hashIndex = hashfn(key); List<Object[]> l = this.table.elementAt(hashIndex); // 遍历链表查找对应key for (Object[] entry : l) { if (key.equals(entry[0])) { @SuppressWarnings("unchecked") V value = (V) entry[1]; return value; } } // 没找到返回null return null; } } public class Main { public static void main(String[] args) { HashT<Integer, String> ht = new HashT<>(10); ht.insert(1, "test"); System.out.println(ht.get(1)); // 输出test } }
关键修复点:
- 移除
new K(key)和new V(value),直接使用传入的key和value实例赋值 - 修正构造函数中
tsize的无效赋值问题 - 初始化
table时为每个位置创建空的ArrayList,避免后续操作抛出NullPointerException - 完善
hashfn方法,使用通用的hashCode()实现哈希计算,兼容更多K类型 - 修正
get方法的参数类型为K,符合泛型设计,并实现查找逻辑 - 修复
get方法的返回值问题,添加类型转换并处理未受检转换警告
内容的提问来源于stack exchange,提问作者notaorb
相关产品推荐
相关产品推荐

