Monday, December 12, 2011

Java - ArrayList

ArrayList class provides methods for basic array operations:
  • add( Object o ) - puts reference to object into ArrayList
  • get( int index ) - retrieves object reference from ArrayList index position
  • size() - returns ArrayList size
  • remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
  • indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
  • clear() - removes all of the elements
Following example ask user for his/her name, and suggests him/her a vacation place.
ArrayList "myarr" is filled with resort names(add method). After user enters his name, we calculate residue of division of user's name length by myarr size -- operation result is a number from 0 to myarr.size()-1 -- which is suitable as array index.
source code: Java
 
 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
 
public class Ex01 { 
 
    public static void main(String[] args) throws IOException { 
 
        BufferedReader userInput = new BufferedReader 
            (new InputStreamReader(System.in));
 
        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("Italian Riviera");
        myArr.add("Jersey Shore");
        myArr.add("Puerto Rico");
        myArr.add("Los Cabos Corridor");
        myArr.add("Lubmin");
        myArr.add("Coney Island");
        myArr.add("Karlovy Vary");
        myArr.add("Bourbon-l'Archambault");
        myArr.add("Walt Disney World Resort");
        myArr.add("Barbados");
 
        System.out.println("Stupid Vacation Resort Adviser");
        System.out.println("Enter your name:");
        String name = userInput.readLine();
        Integer nameLength = name.length();
        if (nameLength == 0) 
        { 
            System.out.println("empty name entered");
            return;
        } 
 
        Integer vacationIndex = nameLength % myArr.size();
 
        System.out.println("\nYour name is "+name+", its length is " + 
                        nameLength + " characters,\n" +
                        "that's why we suggest you to go to " 
                        + myArr.get(vacationIndex));
    } 
} 
 
warning 

  • ArrayList stores only object references. That's why, it's impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.

  • For multi-theaded(synchronized) array class use Vector (java.lang.Vector)

  • No comments:

    Post a Comment