Normally i thought i could just write: listOfObjects.get(0).get("x") and it would return "foo" but that does not work.
No, it wouldn't - because the type of listOfObjects.get(0)
is just Object
. How do you expect the compiler to know that it's meant to be a map?
You can use:
HashMap<String, String> map = (HashMap<String, String>) listOfObjects.get(0);
// Use map...
... but be aware that due to the nature of generics in Java, that cast isn't really ensuring that all the key/value pairs in the map are "string to string". The cast would work even if you'd originally used:
Map<Integer, Integer> badMap = new HashMap<Integer, Integer>();
badMap.put(0, 10);
listOfObjects.add(badMap);
You'll get a warning for this, but it's important to understand what it means. It's not clear what your use case is, but if you can make it more strongly typed (perhaps create a new class which contains a Map<String, String>
?) that would be good. Is every element of your list going to be a map? If so, why are you using List<Object>
rather than a more strongly-typed list? If some elements aren't going to be maps, how can you tell which ones will be? (These are the sort of things you should be thinking about carefully.)