The ArrayList Class

An ArrayList is basically a collection of any type of objects (including the null reference) with an initial capacity. The capactity shows how many object elements you can have in the collection. The capacity grows automatically when you add more elements to the collection.

The details of the ArrayList can be found on the web page : http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html

Two of the constructors for ArrayList are

  1. ArrayList ( ) that sets the initial capacity to 10.
  2. ArrayList ( an_int_value ) that sets the initial capacity to this an_int_value

Sample methods from this class:

Problem

To exprience an array list, generate an array list of 10 elements. The elements will be either a rectangle or a triangle, selected randomly. Then print the array list.

Solution

import java.util.*; /* for Scanner and ArrayList classes */
/* A program to demonstrate the ArrayList class
 * Author : Özlem Özgü
 * Date: 22/11/2007
 * Revision 1.0
 *
 * This class uses the triangle and rectangle classes
 */
 
 public class ArrayList1 {
 	
 	public static void main ( String [ ] args ) {
 		
 		// generate a collection of equileteral triangles or rectangles (random selection)
 		
 		Scanner oku = new Scanner (System.in) ;
 		
 		Random r = new Random() ;
 		
 		int choice;
 		double a, b;
 		
 		ArrayList collection = new ArrayList () ;
 		
 		for (int index=0;index<=9;index++) {
 			choice = r.nextInt(2) ; // choice is either 0 or 1
 			if (choice==0) { // add a rectangle
 			
 				System.out.print ("First side length of a rectangle: ");
 				a = oku.nextDouble () ;
  				System.out.print ("Second side length of a rectangle: ");
 				b = oku.nextDouble () ;
 								
 				collection.add ( new rectangle (a,b) ) ;
 			}
 			else {
 				
 				System.out.print ("Side length of an equilateral triangle: ");
 				a = oku.nextDouble () ;
 				
 				collection.add ( new triangle ( Math.toRadians(60),
 							Math.toRadians(60), Math.toRadians(60), a, a, a) ) ;
 				
 			}
 		}
 		
 		/* output the collection */
 		
 		System.out.println ("***********************************") ;
 		
 		System.out.println ("The collection having " + collection.size () +
 							" elements is : " ) ;
 		
 		System.out.println (collection) ;
 		
 		System.out.println ("***********************************") ;
 		
 		
 	
 	
 	}
 }