问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/13047123/workaround-for-generic-arrays-in-java