[course08] 02 ArrayList
[course08] 02 ArrayList
An ArrayList provides an alternative way of storing a list of objects and has the following advantages over an array:
An ArrayList shrinks and grows as needed in a program, whereas an array has a fixed length that is set when the array is created.
In an ArrayList list, the last slot is always list.size()-1, whereas in a partially filled array, you, the programmer, must keep track of the last slot currently in use.
For an ArrayList, you can do insertion or deletion with just a single statement. Any shifting of elements is handled automatically. In an array, however, insertion or deletion requires you to write the code that shifts the elements.
It is easier to print the elements of an ArrayList than those of an array. For an ArrayList list and an array arr, the statement
System.out.print(list);will output the elements of list, nicely formatted in square brackets, with the elements separated by commas. Whereas to print the elements of arr, an explicit piece of code that accesses and prints each element is needed. The statementSystem.out.print(arr);will produce weird output that includes an @ symbol—not the elements of the array.
The ArrayList Class
private ArrayList<Clown> clowns;
The Methods of ArrayList
// Constructor constructs an empty list.
ArrayList()
// Returns the number of elements in the list.
int size()
// Appends obj to the end of the list. Always returns true. If the specified element is not of type E, throws a run-time exception.
boolean add(E obj)
//Inserts element at specified index. Elements from position index and higher have 1 added to their indices. Size of list is incremented by 1.
void add(int index, E element)
// Returns the element at the specified index in the list.
E get(int index)
// Replaces item at specified index in the list with specified element. Returns the element that was previously at index. If the specified element is not of type E, throws a run-time exception.
E set(int index, E element)
// Removes and returns the element at the specified index. Elements to the right of position index have 1 subtracted from their indices. Size of list is decreased by 1.
E remove(int index)
Autoboxing and Unboxing
An ArrayList cannot contain a primitive type like double or int: It must only contain objects. (It actually contains the references to those objects.) Numbers must therefore be boxedplaced in wrapper classes like Integer and Double—before insertion into an ArrayList.
Autoboxing is the automatic wrapping of primitive types in their wrapper classes
Examples
Last updated
Was this helpful?