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.
Since Map holding a type of Object, you need to cast that result from Object to List.
ArrayList<Integer> list = (ArrayList<Integer>)testMap.get("test");
System.out.println(list.get(0));
And it is bad practise to have Object as a value. Choose most specific type if possible.
Map<String, ArrayList<Integer>> testMap = new HashMap<>();
So that you can avoid casts. With the above declaration you can directly do
System.out.println(testMap.get("test").get(0));
If you have no option but have to use your map with Object type, instanceof is your friend. That helps you to have a check before doing any cast. So that you can avoid ClassCastException
's.
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
if (testMap.get("test") instanceof ArrayList) {
System.out.println(((ArrayList<Integer>) testMap.get("test")).get(0));
}
I'd recommend to define your map as
Map<String, ArrayList<Integer>> testMap = new HashMap<>();
if you are ok with ArrayLists to be values...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With