1

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.

Community
  • 1
  • 1
KCK
  • 2,015
  • 2
  • 17
  • 35

1 Answers1

1

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.

prem kumar
  • 5,641
  • 3
  • 24
  • 36
  • that fixed my problem. Thanks :) now there is no error – KCK Aug 06 '16 at 14:50
  • @James_D whats the problem with that. Raw map type means it can take any object as key and value – prem kumar Aug 06 '16 at 14:51
  • Ah, yes, OK. I thought it wouldn't autobox the ints supplied to the `put(...)` method without specifying a `Map`. It is still bad practice to use raw types, though (and also to use implementation types for the compile-time type). – James_D Aug 06 '16 at 14:55
  • @James_D even i thought of editing my answer about adding int as key. but then I checked in eclipse it accepted though not the right way. Can you remove your down vote plz – prem kumar Aug 06 '16 at 14:57
  • @kashyapkotak can you upvote if the answer was helpful – prem kumar Aug 06 '16 at 14:59
  • i did upvote but my reputation is not enough for that to be counted. But i really dont get the similarity between my question and the one of which mine is duplicate – KCK Aug 06 '16 at 15:06
  • @kashyapkotak ok fine. plz do later if possible. Regarding the duplicate, that link describes why raw types are not used generally. And in your case you were using raw list. – prem kumar Aug 06 '16 at 15:09