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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With