1

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?

3
  • 2
    alB.get(0).get(2) Commented Jun 28, 2018 at 3:26
  • 1
    Possible duplicate of how to get value from 2d arraylist Commented Jun 28, 2018 at 3:28
  • 1
    You need to use generic first like @Mureinik's answer Commented Jun 28, 2018 at 3:33

3 Answers 3

4

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));
Sign up to request clarification or add additional context in comments.

Comments

3

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));

Comments

2

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.