Java .

Java ArrayLists


the ArrayList constructors

ArrayList ArrayListName = new ArrayList();

ArrayList ArrayListName = new ArrayList(5); //The 5 sets the initial element capcaity. The default is 10.

ArrayList ArrayListName = new ArrayList(collectionIn); //creates a new ArrayList with the elements of a collection. //Elements are read from the collection with an Iterator.

ArrayList methods to find out what is in the ArrayList

int arrayListSize = arrayListName.size();

boolean isArrayListEmpty = arrayListName.isEmpty();

int objectFirstFoundAt = arrayListName.indexOf(objectToSearchFor);

int objectLastFoundAt = arrayListName.lastIndexOf(objectToSearchFor);

boolean isObjectInArrayList = arrayListName.contains(objectToSearchFor);

ArrayList methods to retrieve elements from the ArrayList

Object objectName = 
  (ClassTypeToCastTo) arrayListName.get(intOffsetToGetElementAt);
//note: Objects coming out of ArrayLists have lost 
//  their class type, and must be cast

ArrayList methods to alter what is in the ArrayList

boolean addWasGood = 
  //inserts at end

arrayListName.add(intOffsetToSetElementAt, objectToAdd); //inserts at offset, no boolean returned

arrayListName.addAll(collectionToAdd); arrayListName.addAll(intOffsetToAddCollectionAt, collectionToAdd);

arrayListName.set(intOffsetToSetElementAt, objectIn); //replaces element at offset

arrayListName.remove(intOffsetToRemoveElementAt); //deletes element at offset

arrayListName.removeRange (intOffsetToRemoveElementFromInclusive, intOffsetToRemoveElementToExclusive); //deletes from start offset up to the end offset //note - element at the end offset is not deleted


ArrayList methods for Arrays

Object[] arrayToCopyArrayListInto = arrayListName.toArray();


The Java 2 Platform Specification
Thinking in Java by Bruce Eckel
Core Java (TM) 2 Volume 1 - Fundamentals by Cay Horstmann and Gary Cornell
Sign in to be the first to comment on Java ArrayLists.