Initialize a Generic Java Generic Array

So, I have this general HashTable class that I am developing, and I want to use it in general for any number of input types, and I want to also initialize the internal memory array as a LinkedList array (for collision purposes), where each LinkedList is predefined (for type safety) to be a generic type from the HashTable class. How can i do this? The following code best explains my intentions, but of course it does not compile.

public class HashTable<K, V> { private LinkedList<V>[] m_storage; public HashTable(int initialSize) { m_storage = new LinkedList<V>[initialSize]; } } 
+6
java generics hash
source share
2 answers

Generics in Java do not allow the creation of arrays with common types. You can convert the array to a generic type, but this will result in a warning about unverified conversions:

 public class HashTable<K, V> { private LinkedList<V>[] m_storage; public HashTable(int initialSize) { m_storage = (LinkedList<V>[]) new LinkedList[initialSize]; } } 

Here is a good explanation without going into technical details about why creating a universal array is not allowed.

+15
source share

In addition, you can suppress a warning using the annotation method:

 @SuppressWarnings("unchecked") public HashTable(int initialSize) { ... } 
0
source share

All Articles