I have a Map<String, Object>
in which I store "test"
and ArrayList<Integer>
. I then try to display the whole array testMap.get("test")
which works fine, but when I try to display not the whole array but rather its 1st element, it fails with error: cannot find symbol: method get(int)
.
public class Test {
public static void main(String[] args) {
Map<String, Object> testMap = new HashMap<>();
ArrayList<Integer> testArray = new ArrayList<>();
testArray.add(1);
testArray.add(2);
testArray.add(3);
testMap.put("test", testArray);
//works fine, output: [1, 2, 3]
System.out.println(testMap.get("test"));
//get 1st element of testArray, error
System.out.println(testMap.get("test").get(0));
}
}
Why does this happen and how to fix it?
My guess was the type Object
in the Map
causes it, but I can't change it to ArrayList
because the Map
is supposed to store other types (like String
, Integer
) as well. So I tried:
System.out.println((ArrayList) testMap.get("test").get(0));
System.out.println(((List<Integer>) testMap.get("test")).get(0))
didn't work too.
which still resulted in the error.