我有两个类(class)
class Key<T extends Comparable<T>> {// used for composite key for HashMap
private T q;
private T o;
@Override
public boolean equals(Object obj) {
...
}
@Override
public int hashCode() {
....
}
}
class A<Key,V, T> {
private LinkedHashMap<Key,V> map;
public A() {
... suppose we instance map and assign some example values for it here.
}
public foo (T q, T o) {
//From two element q and o, I want to instance a object Key k
//to check whether this key k is exist in the Map or not by using
//map.get(key).
Key k = new Key(q,o);
}
}
但我在 Key k = new Key(q,o)
行收到错误“无法实例化类型键”?
那么为什么会出现这个错误,我该如何解决呢?
最佳答案
Key
被声明为类 A
中的类型变量。
class A<Key, V, T> { ...
^ Everything between <> are type variables
这意味着当您编写 new Key
时,您正在尝试创建“某些”类的实例,不一定是您的 Key
类。由于类型删除,实际类型在运行时是未知的。
假设您要引用此处发布的 Key
类,只需删除类型变量的声明即可:
class A<V, T> { ...
请注意,您也不应该使用原始类型:
private LinkedHashMap<Key<T>,V> map;
Key<T> k = new Key<>(q, o);
此外,您需要绑定(bind)T
以符合Key
的约束,即它必须是可比较的:
class A<V, T extends Comparable<T>> { ...
关于java - 在其他类中实例泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36494640/