Reputation: 122
I have a problem with pulling out a value from an Arraylist
inside an Arraylist
.
I'll just give an example of my problem.
Example:
ArrayList alA = new ArrayList();
ArrayList alB = new ArrayList();
alA.add("1");
alA.add("2");
alA.add("3");
alB.add(alA);
System.out.println(alB.get(0));
This will return [1, 2, 3]
as the result.
In my case I only need to print out 3
. How do I achieve this?
Upvotes: 1
Views: 277
Reputation: 5162
Simply do the following if you don't want to change your other portions of current code
System.out.println(((ArrayList)alB.get(0)).get(2));
Upvotes: 3
Reputation: 816
System.out.println(alB.get(0));
return alB
's 0th index element which is alA
. Since you want the element 3
, you need to get the 2nd index element of alA
, in this case it is alA.get(2);
Combined:
System.out.println(((ArrayList)alB.get(0)).get(2));
Upvotes: 2
Reputation: 311073
Just call get
on the inner array:
System.out.println(((List) alB.get(0)).get(2));
Note that by using generics, you'll eliminate the need to cast:
List<String> alA = new ArrayList<>();
List<List<String>> alB = new ArrayList<>();
alA.add("1");
alA.add("2");
alA.add("3");
alB.add(alA);
System.out.println(alB.get(0).get(2));
Upvotes: 4