[英]Unchecked cast of generic typed method return in Java
提前致歉,我在拼写问题标题的字词方面很费力,我知道这并不理想。
因此,我尝试实现自己的Java HashMap小版本,当然,我希望它可以与泛型一起使用,以使其能够与任何类一起使用,就像真正的HashMap一样。
在我的get(...)
方法中,我传递了一个键并想返回一个值。 一切正常,直到我尝试返回某物为止,然后我得到了普遍要求的Xlint:unchecked
类型安全性警告,指出我的返回值类型无法验证。 请参见以下代码段:
public <K, V> V get (K key) {
if(!(key instanceof Object)) {
System.out.println("ERROR: key given can't be guaranteed to have a hash function");
return null;
}
int hashCode = key.hashCode();
int index = hashCode % items.length;
HashItem slot = items[index];
while(slot != null) {
if(slot.getKey().equals(key)) {
V val = slot.getVal();
return val;
}
slot = slot.getNext();
}
return null;
}
作为参考,请参见.getVal()
的定义:
public V getVal() {
return HashItem.this.val;
}
.getVal()
方法是私有内部类HashItem<K, V>
:
private class HashItem <K, V> {
// blah blah
}
自制的哈希映射类本身的结构如下:
public class MyHash <K, V>
{
// blah blah
private class HashItem <K, V> {
// blah blah
public V getVal() {
return HashItem.this.val;
}
// blah blah
}
public MyHash (int capacity, double newLoadFactor) {
// blah blah
}
// blah blah etc etc
}
由于K
和V
在整个过程中都是恒定的,所以我不明白为什么不能保证.getVal()
的类型或如何解决此问题。 我试过这样的转换: (V)
可以,但是返回未经检查的转换错误。 我也尝试过只是返回值,但是然后我得到的返回类型是Object
,这是不可接受的。
如何获取.getVal()
方法以返回正确的类型?
1.将public <K, V> V get(K key)
更改为public V get(K key)
2.change HashItem slot = items[index];
到HashItem<K, V> slot = items[index];
样例代码:
public class MyHash<K, V> {
// blah blah
private class HashItem<K, V> {
// blah blah
V val;
K key;
public V getVal() {
return HashItem.this.val;
}
public K getKey() {
return HashItem.this.key;
}
public HashItem<K, V> getNext() {
return null;
}
// blah blah
}
HashItem<K, V>[] items;
public V get(K key) {
if (!(key instanceof Object)) {
System.out.println("ERROR: key given can't be guaranteed to have a hash function");
return null;
}
int hashCode = key.hashCode();
int index = hashCode % items.length;
HashItem<K, V> slot = items[index];
while (slot != null) {
if (slot.getKey().equals(key)) {
V val = slot.getVal();
return val;
}
slot = slot.getNext();
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.