Lesson 4.5 -
The ArrayList Class
Purpose: To learn how to work with the ArrayList Class and its methods
Better Arrays We have used what are called simple arrays up to this point. They are simple because they do not have built-in methods - they are not a class. Now we will look at a class that handles array structures in a much more elegant but complicated way - the ArrayList class. Because ArrayList is a class, it contains methods. You will find that these methods streamline many of the tasks involved with process data in arrays. Below is a list of these methods and their decriptions.
Method Summary |
void
|
add(int index, java.lang.Object obj)
Inserts the argument at the specified position in this list. |
boolean
|
add(java.lang.Object obj)
Append (adds) the argument to the end of this ArrayList. |
boolean
|
contains(java.lang.Object obj)
Returns true if this list contains an object equal to the object obj. |
java.lang.Object
|
get(int index)
Returns the element at the specified position in this list. |
int
|
indexOf(java.lang.Object obj)
Returns the first index that contains the element obj or -1 if obj is not in the ArrayList. |
java.lang.Object
|
remove(int index)
Removes the element at the specified position from this list. |
java.lang.Object
|
set(int index, java.lang.Object obj)
Replaces the element at the specified position in this list with the specified object. |
int
|
size()
Returns the number of elements in this list. |
Examples Here are some examples of using these methods
import java.util.ArrayList; // this goes at the top of the program
ArrayList list = new ArrayList(); // declares an empty ArrayList
list.add("Royal"); // adds the String "Royal" to end of list
// list = ["Royal"]
list.add("High"); // adds the String "High" to end of list
// list = ["Royal", "High"]
list.add("School"); // adds the String "School" to end of list
// list = ["Royal", "High", "School"]
list.add(1, "Valley"); // adds the String "Valley" to list at 1
// list = ["Royal", "Valley", "High", "School"]
int x = list.indexOf("School"); // returns index of "School"
// x = 3
list.remove(2); // removes the element at position 2
// list = ["Royal", "Valley", "School"]
list.set(2, "High"); // replaces element at pos 2 with "High"
// list = ["Royal", "Valley", "High"]
SOP(list.size()); // displays the size of list
// Outputs 3 to the screen
String word = (String) list.get(1); //stores element 1 into word
// word = "Valley"
if(list.contains("Simi")) SOP("Yes!"); else SOP("No!");
// Displays "No!"
SOP(list); // displays the entire list
// Outputs ["Royal", "Valley", "High"] to the screen
In closing, ArrayLists store objects. So an item must be a class object to be stored in an ArrayList. This also means that these objects must be typecast when they come out if they need to be handled in their original form. |