Reputation: 136
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.)
Upvotes: 0
Views: 68
Reputation: 4274
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]
}
}
Upvotes: 1