Java Chapter 12 - ArrayList
ArrayList is a Java class that provides an automatic resizable array. Normal arrays are not dynamic and cannot be resized after they are created. The ArrayList class includes methods to add, remove, and search for elements. It can be implemented to do database and data structure functions.
12.1 ArrayList Methods
To use the ArrayList class, you must
first import java.util.*
Use the following statements to work with the ArrayList class:
Statement | Description |
ArrayList<String> myColors = new ArrayList<String>(); | Declare a ArrayList of string elements named myColors. |
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); | Declare a ArrayList of integer elements name myNumbers. |
myColors.add("purple"); myColors.add("orange"); myColors.add("green"); |
Adds an item to the end of the ArrayList. In this case, "purple" is index 0, "orange" is index 1, and "green" is index 2. |
myColors.size(); | Returns the size of the ArrayList. In this case, the size is 3. |
myColors.indexOf("green"); | Searches the ArrayList for the string and returns its index of. "green" will return 2. If the string is not found, it will return -1. |
myColors.get(1); | Returns the item at index 1. In this case, it returns "orange" |
myColors.set(1,"yellow"); | Replaces the item at position 1. In this case, "orange" is replaced with "yellow". |
myColors.contains("red"); | Returns true or false depending if "red" is contained in the ArrayList. |
myColors.remove(x); | Removes the item at position x. |
myColors.subList(x,y); | Returns a sub list of myColors from position x to position y-1. |
myColors.removeRange(x,y); | Removes all elements inclusively between index x and y. |
myColors.add(x, item); | Adds an item at position x. |
myColors.clear(); | Removes all elements in the ArrayList. |
12.2 Example ArrayList of Strings
The following is an example program using an ArrayList of Strings:
PeriodicTable.java |
import java.util.*; |
Output |
Size = 4 |
12.3 Example ArrayList of Objects
The following is an example program using an ArrayList of objects (MonsterClass):
creepy.java |
import java.util.*; |
Output |
Size = 4 |