-1

I'm getting error while accessing the size or element of inner list in Java.

This is the Error I'm getting

public static void main(String... args) {
    List list = new ArrayList();

    List<Integer> list2 = Arrays.asList(1,2,3);
    List<Integer> list3 = Arrays.asList(5, 6);
    List<Integer> list4 = Arrays.asList(7, 8, 9);

    list.add(list2);
    list.add(list3);
    list.add(list4);

    for (int i = 0; i < list.size(); i++) {
        for (int j = 0; j < list.get(i).size(); j++) {
            System.out.print(list.get(i).get(j)+ " ");
          }
       }
    }
}
Nishchay
  • 1
  • 2

3 Answers3

1

Your declaration of the list q is missing the information of what kind of objects it contains.

List<List<Integer>> q = new ArrayList<>();

Without this information, the only thing the compiler can know is that it contains objects of some kind, so q.get() must have type Object. But there are no get() nor size() methods in Object class, and that's the error you get.

Joni
  • 108,737
  • 14
  • 143
  • 193
0

You should be using List<List<Integer>> q = new ArrayList<>(); instead of List q = new ArrayList(); since you are inserting a group of lists in q.

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

Update you loop code with following, basically you need to cast the q.get(i) into List.

 for (int i = 0; i < q.size(); i++) {
        for (int j = 0; j < ((List) q.get(i)).size(); j++) {
            System.out.print(((List) q.get(i)).get(j)+ " ");
          }
       }
    }

Hope this helps.

Reeta Wani
  • 197
  • 4
  • 13