kashyap kotak kashyap kotak - 3 months ago 8
Java Question

adding TreeMaps to ArrayList in loop

I want to add treemaps to an arraylist in java. Here's what I am doing:

ArrayList al=new ArrayList();
for(int i=0;i<n;i++)
{
al.add(new TreeMap());
}


the when I try to add key value pairs to the treemap:

for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
al.get(i).put(j,(arr[j]-arr[i]));
}
}


The compiler gives error in this:
error description

can someone please help me out....
Thanks.

this question is different from What is a raw type and why shouldn't we use it? because here I am not asking for an explanation of raw types or generics, but I am asking for the solution of an error.

Answer

You need to use Generics.

ArrayList<TreeMap> al=new ArrayList<TreeMap>();
for(int i=0;i<n;i++)
{
    al.add(new TreeMap());
}

Or you have to do casting. Generics is better option.

Explanation: If you use ArrayList al=new ArrayList(); which means array list of objects. But when you try to add a key value pair to the map, you first get the object in your case and this is Object type. To use it as tree map you need to cast it to TreeMap.

If you use ArrayList<TreeMap> al=new ArrayList<TreeMap>(); then while getting an array entry you directly get TreeMap.

Comments