Workaround for generic arrays in java

醉酒当歌 提交于 2020-01-15 04:05:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!