Java generation error

Possible duplicate:
Java how to create a Generic Array
Error: creating a Generic Array

I get this error:

Cannot create a generic array of T 

This is my code (error on line 6):

 1 public class HashTable<T> { 2 3 private T[] array; 4 5 HashTable(int initSize) { 6 this.array = new T[initSize]; 7 } 8 } 

I wonder why this error appears, and the best solution to fix it. Thanks.

UPDATE:

I adjusted my code so that the array accepts in linked lists instead, but I get a new error.

Here is my mistake:

 Cannot create a generic array of LinkedList<T> 

Here is my code (error on line 6):

 1 public class HashTable<T> { 2 3 private LinkedList<T>[] array; 4 5 HashTable(int initSize) { 6 this.array = new LinkedList<T>[initSize]; 7 } 8 } 

Is this error the same reason? I just assumed that I could create common linked lists and just store them in an array.

+6
source share
3 answers

The generated arrays can be created using reflection (although unsafe selection is required), you just need to pass the class as a parameter (provided that the following class is inside the class that defines a parameter of type <T> ):

 @SuppressWarnings("unchecked") public T[] createArray(Class<T> klass, int size) { return (T[]) Array.newInstance(klass, size); } 

For example, in your case:

 HashTable<Integer> t = new HashTable<Integer>(); Integer[] intArray = t.createArray(Integer.class, 4); intArray[0] = 1; intArray[1] = 2; intArray[2] = 3; intArray[3] = 4; System.out.println(Arrays.toString(intArray)); > [1, 2, 3, 4] 
+3
source

Yes, shared arrays cannot be created. The best workaround I know is to use collections:

 private List<T> list; ....... list = new ArrayList<T>(); 
+8
source

You cannot create T (in Java), but T [] internally matches Object [].

 public class HashTable<T> { private T[] array; @SuppressWarnings("unchecked") HashTable(int initSize) { this.array = (T[]) new Object[initSize]; } } 

(Will compile, I checked)

Due to newacct's comments, it's probably best to just use Object [] and pass the elements to T.

 public class HashTable<T> { private Object[] array; public HashTable(int initSize) { this.array = new Object[initSize]; } public void put(String pKey, T pItem) { ... array[x] = pItem; .... } public T get(String pKey) { ... return (T) array[x]; } } 
+2
source

Source: https://habr.com/ru/post/914633/


All Articles