0

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?

freakout
  • 53
  • 1
  • 1
  • 11

2 Answers2

5

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.

sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • It's a LinkedHashMap and I get incompatible types when not casting. – freakout May 24 '13 at 17:35
  • 1
    @freakout you should [program oriented to interfaces, not to implementations](http://stackoverflow.com/q/383947/1065197). By doing that, you won't have any casting problem. – Luiggi Mendoza May 24 '13 at 17:36
  • It is working! The problem seems to be my while loop to iterate through the data. Your for loop works perfectly, thank you! – freakout May 24 '13 at 17:38
  • Yeah I know, Eran, but the way sanbhat presents here is much cleaner and easier to understand. – freakout May 24 '13 at 17:40
  • 1
    @LuiggiMendoza But looping with an iterator is the only possible option in some cases (such as the case when you want to be able to remove items from the collections while iterating). – Eran May 24 '13 at 17:44
  • @Eran I never said that using iterator is wrong. Back to OP's problem, this is not the case :). – Luiggi Mendoza May 24 '13 at 18:54
  • @LuiggiMendoza Well, if we're back to OP's problem - OP used an explicit iterator in the question, which is why I used one in my answer :) – Eran May 24 '13 at 23:54
  • @Eran that doesn't stop us to show OP other ways to solve the problem :). – Luiggi Mendoza May 25 '13 at 00:29
0
ArrayList<MyObject> value = e.getValue();

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

Map<Integer, ArrayList<MyObject>>
Vegard
  • 1,802
  • 2
  • 21
  • 34