我有这个方法:
public V get(K key){
TableEntry wanted = table[Math.abs(key.hashCode() % table.length)];
while(wanted.getKey() != key && wanted != null) wanted = wanted.next;
if(wanted.getKey() == key) return wanted.value;
return null;
}
返回 wanted.value 在 Eclipse 中带有红色下划线,我收到消息:无法将表单对象转换为 V。我的问题是:为什么我可以这样做?我想返回值(值是类型 V)。这是我的代码: Java code
最佳答案
为了在 java 中使用泛型,您需要使用您将要使用的泛型类型来声明类。
如果您希望 getValue()
返回 Object 以外的类型,则应使用泛型声明 TableEntry
,在您的情况下,它应该是:
TableEntry<K,V> wanted = table[Math.abs(key.hashCode() % table.length)];
这将使 getValue() 返回 V(如果您不那样声明,K 和 V 将自动定义为对象)
关于java - 无法访问类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451385/