get element from arraylist of arraylist in java code example

Example 1: Lists inside lists in java

public class GuiTest {

	
	public static void main(String[] args) {
		List> MainList = new ArrayList>();
		Random NewRandomNumber = new Random();
		
		for (int i = 0; i < 10; i++) {
			List SecondList = new ArrayList();
			MainList.add(SecondList);
			for (int i2 = 0; i2 < 10; i2++) {
				SecondList.add(NewRandomNumber.nextInt(6));
			}
		}

Example 2: get number of items in arraylist java

import java.util.ArrayList;

/*
 * Java Program to find the length of ArrayList. *
 */

public class ArrayListDemo{

  public static void main(String[] args) {
    System.out.println("Welcome to Java Program to find the length of array list");

    ArrayList listOfBanks = new ArrayList<>();
    int size = listOfBanks.size();
    System.out.println("size of array list after creating: " + size);

    listOfBanks.add("Citibank");
    listOfBanks.add("Chase");
    listOfBanks.add("Bank of America");
    size = listOfBanks.size();

    System.out.println("length of ArrayList after adding elements: " + size);

    listOfBanks.clear();
    size = listOfBanks.size();
    System.out.println("size of ArrayList after clearing elements: " + size);
  }

}
Output
Welcome to Java Program to find length of array list
the size of array list after creating: 0
the length of ArrayList after adding elements: 3
the length of ArrayList after clearing elements: 0

Example 3: arraylist of arraylist

public static void main(String[] args) {
    ArrayList> outer = new ArrayList>();
    ArrayList inner = new ArrayList();        

    inner.add(100);     
    inner.add(200);
    outer.add(inner); // add first list
    inner = new ArrayList(inner); // create a new inner list that has the same content as  
                                           // the original inner list
    outer.add(inner); // add second list

    outer.get(0).add(300); // changes only the first inner list

    System.out.println(outer);
}

Tags:

Misc Example