Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map of Objects, can't access ArrayList element by index [closed]

Tags:

java

arraylist

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.

like image 546
Ans Avatar asked Dec 02 '22 11:12

Ans


2 Answers

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));
    }
like image 63
Suresh Atta Avatar answered Jan 10 '23 23:01

Suresh Atta


I'd recommend to define your map as

Map<String, ArrayList<Integer>> testMap = new HashMap<>();

if you are ok with ArrayLists to be values...

like image 34
Betlista Avatar answered Jan 10 '23 22:01

Betlista