public class XXXX{
private List<Integer>[] a;
public XXXX(int num)
{
a = new ....?
}
}
How should i new the a ?
public class XXXX{
private List<Integer>[] a;
public XXXX(int num)
{
a = new ....?
}
}
How should i new the a ?
NPE: "Arrays and generics don't go well together"
Go for list of lists
List<List<Integer>> a = new ArrayList<List<Integer>>();
or double array
int[][] a = new int[5][5];
You can create an array of lists but you cannot use type during initalization.
List<Integer>[] lists=new List[10];
//insertion
for(int i=0;i<10;i++){
lists[i]=new ArrayList<Integer>();
lists[i].add(i);
lists[i].add(i+1);
}
//printing
for(List<Integer> list:lists){
System.out.println(list.size());
}
Why this works? Because the lists
variable points to an array data structure whose data type is List<Integer>
. This array contains a set of references to different objects of type List<Integer>
, and this is why if we try to run lists[i]=new ArrayList<String>();
it will not compile. However when we initialize the array itself we don't need to provide the type of the List objects as List since from JVM point of view a List of Integer objects and a List of Object objects will require the same number of bytes as logn as their sizes is same. The only constraint comes when we set a array member to a value (of type List - it has to be List<Integer>
not anything else)
You can type cast the List[]
to a List<Integer>[]
but the end result and the JVM behavior is the same.
This works
int arraySize = 10;
List<Integer>[] a = (List<Integer>[]) new List[arraySize];
It create an array (of size 10) that can contains List of Integer
List is an interface in java!
you can give references of instances like ArrayList, linket list, vector and stack to a variable with List datatype
so you can use one of the following,
a = new ArrayList<Integer>();
a = new LinkedList<Integer>();
a = new Vector()<Integer>;
a = new Stack()<Integer>;