CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
ArrayList class
Class

An ArrayList is an indexed list of references that can grow as the number of data increases.

The ArrayList class

java.util.ArrayList

An introduction to array lists

  • An array list is a collection that's similar to an array, but can change its capacity as elements are added or removed. It is dynamically resizable.
  • The ArrayList class uses an array to store the elements it contains.
  • You cannot use an ArrayList to store primitive types.
  • You can specify the type of elements to be stored in the array list by naming a type in angle brackets.
  • You must cast elements to the appropriate reference type or you must declare a reference type in the ArrayList declaration.
  • You can specify the size of an array list when you create it, or you can let the array list default to an initial capacity of 10 elements.
  • The capacity of an array list automatically increases whenever necessary.

Constructors of the ArrayList class

Constructor Description
ArrayList() Creates an empty array list with an initial capacity of ten objects of the specified type.
ArrayList(intCapacity) Creates an empty array list with the specified capacity.
ArrayList(Collection) Creates an array list containing the elements of the specified collection.

Common methods of the ArrayList class

Method Description
add(object) Adds the specified object to the end of the list.
add(index, object) Adds the specified object at the specified index position.
clear() Removes all elements from the list.
contains(object) Returns true if the specified object is in the list.
get(index) Returns the object at the specified index position.
indexOf(object) Returns the index position of the specified object.
isEmpty() Returns true if the list is empty.
remove(index) Removes the object at the specified index position.
remove(object) Removes the specified object.
set(index, object) Sets the element at the specified index to the specified object.
size() Returns the number of elements in the list.
toArray() Returns an array containing the elements of the list.

Previous | Class | Code | Which is Better? | Next