繁体   English   中英

无法访问类的属性

[英]Cannot access to attribute of class

我有这个方法:

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;
    }

在 Eclipse 中返回想要的值是红色下划线,我收到消息:无法将表单对象转换为 V。我的问题是:为什么我可以这样做? 我想返回值(值是类型 V)。 这是我的代码: Java 代码

为了在 Java 中使用泛型,您需要使用将要使用的泛型类型来声明类。 如果您希望getValue()返回该对象以外的类型,则应使用泛型类型声明TableEntry ,在您的情况下,它应该是:

TableEntry<K,V> wanted = table[Math.abs(key.hashCode() % table.length)]; 

这将使 getValue() 返回 V (如果您不那样声明它,K 和 V 将自动定义为对象)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM