javacodex.com
Java Examples
Java Examples
memu home questions

Array Of ArrayLists

This java example creates an array of Arraylists then populates each Arraylists with a random number of entries.

After that the size of each ArrayList in the Array is printed out.

Source: (ArrayOfArrayLists.java)

import java.util.*;
 
public class ArrayOfArrayLists {
 
  public static void main(String[] args) {
 
    Random r = new Random();
 
    // create array of ArrayLists
    ArrayList[] list = new ArrayList[10];
 
    for(int i=0; i<list.length; i++){
      // initialize each ArrayList
      list[i]=new ArrayList<Integer>();
 
      // populate ArrayList
      for(int j=r.nextInt(100);j>0 ; j--){
        list[i].add(j);
      }
    }
 
    // Show size of each Arraylist in the Array
    for(int i=0; i<10; i++){
      System.out.println("list["+i+"].size:: " + list[i].size());
    }
 
  }
}
 

Output:

$ java ArrayOfArrayLists
list[0].size:: 40
list[1].size:: 49
list[2].size:: 97
list[3].size:: 34
list[4].size:: 28
list[5].size:: 98
list[6].size:: 77
list[7].size:: 89
list[8].size:: 95
list[9].size:: 87

Contact: javacodex@yahoo.com