2017-03-13 113 views
0

我试图在Java中实现HashMap,但在尝试返回值时出现此错误。这是Entry类:返回通用类型时不兼容的类型

public class Entry<K,V> { 
private K key; 
private V value; 
public Entry next; 
public Entry(K key, V value) 
{ 
    this.key = key; 
    this.value = value; 
} 

public K getKey() { 
    return key; 
} 

public V getValue() { 

    return value; 
} 

public void setValue(V value) { 
    this.value = value; 
} 
} 

这是我想回到什么:

private Entry[] buckets = new Entry[255]; 


    public V getValue(K key){ 
    int hash = key.hashCode()%buckets.length-1; 
    Entry currentEntry = buckets[hash]; 
    while (currentEntry!=null) 
    { 
     if (currentEntry.getKey().equals(key)){ 
      return currentEntry.getValue(); //error here 
     } 
    currentEntry = currentEntry.next; 
    } 

    return null; 
    } 

我得到的错误是Error:(47, 45) java: incompatible types: java.lang.Object cannot be converted to V

+3

我怀疑'Entry currentEntry'应该是'Entry currentEntry';也用'桶'。 –

+1

...并且按原样,此代码应该发出“未经检查”的警告。 – dhke

+2

并且'int hash = key.hashCode()%buckets.length-1'也有问题,因为它可以返回值为'-1'的值,这会在以下语句中引发异常。 –

回答

-1

您需要通用添加到您的声明:

Entry<K,V> currentEntry = buckets[hash]; 
+1

泛型不适用于数组。 '不能创建条目'的通用数组''。你尝试编译这个吗? –

0

Entry有类型参数,但你也有一组Entry。两人不会在一起。您有许多选项,包括:

  • Entry中删除类型参数并使用不安全的转换。
  • 取而代之的是使用数组,而不是使用数组,将一些描述转到List
  • 废除Entry对象并使用探测算法与Object[]阵列和不安全的强制转换。
  • 使用不安全的转换来初始化buckets
  • 用树替换整个算法。
0

我已经在第1行修改了你的getValue方法签名,下面对我很好。 还在第3行添加了泛型,并使用Entry值初始化。

尽管第2行代码,散列初始化我觉得很差,但不能评论很多,除非我们看到你的把(K键,V值)方法。

public <K> V getValue(K key){ // line 1 
     int hash = key.hashCode()%buckets.length-1; // line 2 
     Entry<K, V> currentEntry = buckets[hash]; //line 3 
     while (currentEntry!=null) 
     { 
      if (currentEntry.getKey().equals(key)){ 
       return currentEntry.getValue(); 
      } 
     currentEntry = currentEntry.next; 
     } 

     return null; 
}