Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have an Array of a collection?

I was trying create an array of a collection as follows.

ArrayList<Integer> ar[]=new ArrayList<Integer>[50];

but it gives me an error -> generic array creation can anybody explain me why is it?

like image 442
sumit sharma Avatar asked Jan 07 '13 08:01

sumit sharma


People also ask

Can a collection be an array?

I'm occassionally irked by the fact that a collection of DOM elements (more formally called a NodeList ) can't be manipulated like an array, because it isn't one.

How do you create an array of collections?

To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T… a) that converts the array into a Collection.

Is an array a collection type?

An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier.

Is an array a collection object?

Arrays are collections of objects with the same type of a defined size. We access elements in an array using an index object, and can initialize arrays both with and without elements.


1 Answers

You can't create arrays of generic types. Use collection of collections instead:

ArrayList<ArrayList<Integer>> = new ArrayList<ArrayList<Integer>>();

Why can't we create an array of generic type? Array stores they exact type internally, but due to the type erasure at runtime there will be no generic type. So, to prevent you from been fooled by this (see example below) you can't create an array of generic type:

//THIS CODE WILL NOT COMPILE
ArrayList<Integer>[] arr = new ArrayList<Integer>[5];
Object[] obj = arr;
obj[0] = new ArrayList<Long>(); //no one is safe
like image 162
Dmitry Zaytsev Avatar answered Nov 04 '22 23:11

Dmitry Zaytsev