2017-02-23 72 views
-1

我试图创建一个数组条目< K,V>元素。有了这段代码,我得到了java.lang.ClassCastException。我怎样才能解决这个问题?java.lang.ClassCastException Object to HashTable.Entry

public class HashTable<K, V> { 
    private final int INITIAL_SIZE = 128; 
    private Entry<K, V>[] table; 

    public HashTable() { 
     table = (Entry<K,V>[]) new Object[INITIAL_SIZE]; 
    } 

    static class Entry<K, V> { 
     // Here comes constructor and other stuff 
    } 
} 
+0

您无法从对象数组创建映射。 – Nicolas

+0

@Nicolas我想创建一个数组,我将在那里存储条目。这是不可能的吗? – tarexme

+0

那么你可以这样做'List > list = new ArrayList <>()' – Nicolas

回答

0

试试这个:

table = (Entry<K, V>[]) new Map.Entry[INITIAL_SIZE]; 
+0

所以这里正确的解决方案是 table =(Entry [])new Entry [INITIAL_SIZE] – tarexme

0

当然你也可以创建自己的Array或进入Abhilekh辛格和萨科列表显示你如何做到这一点。

但是对于典型的用例,java已经有了这样一个Class。它是java.util.Map(即通用接口),最常用的实现方式是java.util.HashMap

您可以使用put(key, value)向该地图添加条目,并且可以使用entrySet获取Set>。