Piumi Wandana
Piumi Wandana

Reputation: 228

how to get value from 2d arraylist

i have arraylists named sub and main,

ArrayList main = new ArrayList();

ArrayList sub=new ArrayList();

i add value to sub and then add sub to main.

example;

 sub.add(1);
 sub.add(2);
 main.add(sub);

now i want to get all values inside sub

 so i used following one but .get(j) gives me the error get >> canot find symbol

for (int i=0;i<main.size();i++) {
       System.out.println();

       for (int j=0;j<sub().size();j++) {
            System.out.print(main.get(i).get(j));//error line
       }
}

how can i get all values inside subarray of main arraylist

Upvotes: 3

Views: 27995

Answers (3)

Dhanushka Gayashan
Dhanushka Gayashan

Reputation: 724

Go through the following code

public class ArrayListDemo {

  public static void main(String[] args) {

      List<List<Integer>> main = new ArrayList<>();
      List<Integer> sub = new ArrayList<>();

      sub.add(1);
      sub.add(2);
      main.add(sub);

      //If you want to get values in sub array list
      for(int i = 0; i < 1; i++){
          List<Integer> arr = main.get(i);
          for(Integer val : arr) System.out.println(val + "");
      }

      //If you want to print all values
      for(List<Integer> list : main){
          for(Integer val : list) System.out.println(val + "");
      }

  }

}

In the above code, I had declared an ArrayList (main) to keep all Array which are having Integer values. Also i had declared an another ArrayList (sub) to keep all Integer values. I had used ArrayList data structure because of length of the List will be changing the run time.

Good Luck !!!

Upvotes: 1

misberner
misberner

Reputation: 3688

Generics could be your friend here:

ArrayList<ArrayList<Object>> main = new ArrayList<ArrayList<Object>>(); // or new ArrayList<>(); in Java 7+
ArrayList<Object> sub = new ArrayList<Object>(); // or new ArrayList<>();

If you can't or don't want to use generics, the solution is to cast the expression main.get(i) to an ArrayList first:

System.out.println(((ArrayList) main.get(i)).get(j));

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83557

When you declare a variable as

ArrayList main;

This list holds Objects. This means that main.get(i) will only return an Object, even if you add ArrayLists. That's why you get a compiler error: Object doesn't have a method named get().

To fix the problem, you need to use generics:

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

ArrayList<Integer> sub=new ArrayList<>();

Now get() will return a List<Integer> which has a get() method, so the compiler error will disappear.

Upvotes: 3

Related Questions