0
import java.util.ArrayList;

public class ArrayListPractice {
   public static void main(String[] args){
        ArrayList arr = new ArrayList();
        arr.add(10);
        arr.add(20);
        // arr is now [10,20]
        ArrayList arr2 = new ArrayList();
        arr2.add(new ArrayList(arr));
        arr2.add(30);
        // arr2 is now [[10,20],30]
        System.out.println(arr2.get(0)); // Prints out [10,20]
   }
}

I can print out the first element of arr2. But how can I print out the first element of the first element? (I want to print out 10 from arr2.)

1
  • If you're using Java 5 or later, please consider using ArrayList<Integer> arr etc. so that you can make use of the type information. The concept is "Generics". Commented Apr 11, 2017 at 12:34

1 Answer 1

1

You need to cast arr2.get(0) to ArrayList so you can call the get method on it (your ArrayList ArrayList arr = new ArrayList(); is not typed - so it holds instances of Object).

Like this:

package test;
import java.util.ArrayList;

public class ArrayListPractice {
   public static void main(String[] args){
        ArrayList arr = new ArrayList();
        arr.add(10);
        arr.add(20);
        // arr is now [10,20]
        ArrayList arr2 = new ArrayList();
        arr2.add(new ArrayList(arr));
        arr2.add(30);
        // arr2 is now [[10,20],30]
        System.out.println(((ArrayList)arr2.get(0)).get(0)); // Prints out [10]
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should use the generic way.

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.