top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10]; [CLOSED]

0 votes
578 views
Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10]; [CLOSED]
closed with the note: Problem solved.
posted Mar 14, 2016 by Shivam Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

We are not allowed to create generic arrays because array carry type information of it’s elements at runtime. This information is used at runtime to throw ArrayStoreException if elements type doesn’t match to the defined type. Since generics type information gets erased at runtime by Type Erasure, the array store check would have been passed where it should have failed. Let’s understand this with a simple example code.

List<Integer>[] intList = new List<Integer>[5]; // compile error
Object[] objArray = intList;
List<Double> doubleList = new ArrayList<Double>();
doubleList.add(Double.valueOf(1.23));
objArray[0] = doubleList; // this should fail but it would pass because at runtime intList and doubleList both are just List

Arrays are covariant by nature i.e S[] is a subtype of T[] whenever S is a subtype of T but generics doesn’t support covariance or sub-typing. So if we would have been allowed to create generic arrays, because of type erasure we would not get array store exception even though both types are not related.

answer Mar 15, 2016 by Rohit
+1 vote

An array stores a fixed-size sequential collection of elements of the same type. so due to the size of object we have to define and initialize with same type of object.

answer Mar 15, 2016 by Manoj Goswami
...