freakout
freakout

Reputation: 53

Cast to ArrayList

I've stored an ArrayList in a Map and I'm trying to get this ArrayList back:

//init map with data: Map<Integer, ArrayList<MyObject>>
while(iterator.hasNext()) {
  Entry entry = iterator.next();
  ArrayList value = (ArrayList)entry.getValue();
}

The cast of the entry.getValue() to a general ArrayList seems to work, however when I try to cast it to the specific ArrayList:

ArrayList<MyObject> value = (ArrayList<MyObject>)entry.getValue();

the compiler throughs an error. Some sort of "Warning from last compilation". Is it possible to cast it to my specific ArrayList so that I can loop through it with a For-Each-Loop afterwards?

Upvotes: 0

Views: 1235

Answers (2)

Vegard
Vegard

Reputation: 1932

ArrayList<MyObject> value = e.getValue();

should be ok, no need to cast because you have defined the right type:

Map<Integer, ArrayList<MyObject>>

Upvotes: 0

sanbhat
sanbhat

Reputation: 17622

If you are creating Map like this

Map<Integer, ArrayList<MyObject>> map = new HashMap<Integer, ArrayList<MyObject>>();

you don't need to cast, and hence there is no WARNING.

for(Entry<Integer, ArrayList<MyObject>> e : map.entrySet()) {
    Integer key = e.getKey();
    ArrayList<MyObject> value = e.getValue();
}

Introduction to Generics was done, to basically avoid these kinds of warnings. With generics we should define the "type" of objects we would like to store in the data-structure. Hence while retrieving, the Java compiler knows exactly what object the data-structure is returning.

Upvotes: 5

Related Questions