ArrayList Methods in Java
The Java computer programming language provides a built-in list interface, which defines an ordered sequence of items and the operations that can be performed on it. One actual implementation of the list interface is the ArrayList class. Together, they provide a convenient way for Java programmers to manage a sequence of items, by taking care of the low-level details of item management while ensuring efficient performance.
-
Collection methods
-
ArrayList inherits the collection methods, which define operations to manipulate the ArrayList items, from the Collection interface. The most important, the "add()" and "remove()" methods, allow the insertion and removal of a certain item from the ArrayList. Bulk insertions and removals are also possible with the "addAll()" and "removeAll()" methods. Other methods -- such as the "size()," "isEmpty()," "contains()" and "containsAll()" -- report the states of the ArrayList to the programmer.
Positional Access and Search Methods
-
The most common positional access methods are the "get()" and "set ()" methods, which retrieve and replace the list item at the specified index. The "add()" and "remove()" methods also provide individual manipulation of list items based on certain index values. The methods "indexOf()" and "lastIndexOf()" allow programmers to search the ArrayList and return the indices of the first and last occurrences of the item, respectively. The Java API documentation for ArrayList provides a detailed description of these methods.
-
Range View Methods
-
Range view methods such as the "subList()" method return a half-open range -- a sub-list that contains items of the original list, from the starting index inclusively up to the ending index exclusively. Oracle.com strongly advises against modifying the original list in any way through the resulting sub-list, which should, if possible, be specified as transient.
Other List Methods
-
Other list methods let Java programmers to perform generic list operations. For instance, the "sort()" method serves as an efficient sorting algorithm for the items in the list. The "shuffle()" and "reverse()" methods, as their names imply, can modify the order of the items in the list, while the "swap()" method allows programmers to exchange the values of two list items.
-
References
Resources
- Photo Credit Jupiterimages/Photos.com/Getty Images