Java中泛型数组的解决方法 [英] Workaround for generic arrays in java
问题描述
我有一个任务,我需要创建自己的(简单)通用链表:
public class Node< T> ; {
private int key;
私人T数据;
私人节点< T> nextNode;
}
但是我需要用哈希表实现一个字典。我想制作一个包含节点的列表。如果发生冲突(两个类型的对象分散到同一个节点,我只需链接它们 - 链表)。
我必须自己实现这个,没有外部帮助(已经实施的清单或以往)
我是如何做到这一点的:
public class GenericDictionary< T>实现GenericDictionary_interface< T> {
private int capacity;
私人节点< T> []插槽;
public GenericDictionary(){
this.capacity = 31;
slots =新节点< T> [容量]; //我需要分散到
}
}
的数组然而并不完全可能。我尝试了解这个主题,试着在这里搜索......但是我没有得到它。
我唯一的要求是...不要对变量/方法的名字不要太在意,让它们易于理解。 解决方案
以下是你可以做的最好的:
@SuppressWarnings(unchecked)
节点< T> [] slots =(Node< T> [])新节点<> [容量];
你不能摆脱警告(除了压制它)。当你需要一个泛型类的数组时,你需要创建一个未指定泛型类型的数组,然后进行转换。
I have an assignment and I need to make my own (simple) generic linked list:
public class Node<T> {
private int key;
private T data;
private Node<T> nextNode;
}
But I need to implement a dictionary with a hash table. I wanted to make a list containing Node(s). In case of a conflict (two objects of type disperse to the same node, I simply link them - linked lists).
I have to implement this by myself, no outside help (already implemented lists or what ever)
How I wanted to do this:
public class GenericDictionary<T> implements GenericDictionary_interface<T> {
private int capacity;
private Node<T> [] slots;
public GenericDictionary () {
this.capacity = 31;
slots = new Node<T>[capacity]; // the array I need which I disperse to
}
}
This however is not exactly possible. I did try and read on the subject, tried searching here on SO ... but I didn't get it at all.
My only request is ... don't be lazy on variable / method names, make them easy to understand please.
Here's the best you can do:
@SuppressWarnings("unchecked")
Node<T>[] slots = (Node<T>[]) new Node<?>[capacity];
You can't get rid of the warning (aside from suppressing it). When you need an array of a generic class, you need to create the array with unspecified generic type then cast it.
这篇关于Java中泛型数组的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!