可能重复:结果 的Java如何:通用阵列创建结果 错误通用阵列创建
我一直负责Java编写一个哈希表,它必须与任何数据类型。都在code我写的规则如下: - 散列表必须有一个数组为标的数据结构,在当时确定的大小的对象被构造 - 当碰撞发生时,碰撞应放入一个链表的元件,其中包含的所有元件中的该索引(key)的哈希表
I have been tasked with writing a Hash Table in Java, which must work with any data type. The rules on the code I am writing are as follows: - The hash table must have an array as the underlying data structures, of a size determined at the time the object is constructed - When a collision occurs, the element that collides should be placed into a linked list, which holds all of the elements at that index (key) in the hash table
因此,对于基本数据类型,我已经LinkedList的类型的数组(定制,而不是Java API的LinkedList)。
Thus, for the underlying data type, I have made an array of type LinkedList (custom, not the Java API LinkedList).
private LinkedList<T>[] table;的问题是,当然,实例化此数组。下面是我的一些尝试:
The issue is, of course, instantiating this array. Here are some of my attempts:
public HashTable(int size) { table = new LinkedList<T>[size]; }这将引发编译时泛型数组创建错误。
This throws a compile-time generic array creation error.
public HashTable(int size) { table = (LinkedList<T>[])(new Object[size]); }在运行时会导致 ClassCastException异常错误(的java.lang.Object 不能转换到的LinkedList )。
前往该项目的人也是不确定如何处理这个问题。有什么办法,我可以改变我的code,使哈希表仍然有一个数组作为其底层的数据结构与碰撞被放置在一个链表?
The person heading the project is also unsure of how to deal with this issue. Is there any way I can change my code so that the hash table still has an array as its underlying data structure with the collisions being placed in a LinkedList?
推荐答案这为我工作:
public class HashTable<T> { private LinkedList<T> table[]; @SuppressWarnings("unchecked") public HashTable(int size) { table = new LinkedList[size]; } }例如:
HashTable<String> t = new HashTable<String>(10); t.table[0] = new LinkedList<String>(); t.table[0].add("test"); System.out.println(t.table[0].get(0));是的,构造函数产生一个警告(即解释了未登记的注释),但事后code工作没有更多的警告。
Yes, the constructor generated a warning (that explains the "unchecked" annotation), but afterwards the code works without more warnings.
更多推荐
Java泛型:包含数组泛型
发布评论