Introduction to ArrayLists
An ArrayList is a class that encapsulates an array and provides a number of convenient methods to simplify storing collections of like data.
Introduction
- Like an array, an
ArrayListstores a collection of similar data. - Unlike an array, an
ArrayListcan only store reference types (no primitives). ArrayLists use a generic between angle brackets to specify the type stored within the object. For example, creating anArrayListofStrings looks like this:ArrayList<String> words = new ArrayList<>();- The left side of the assignment operator declares a reference,
words, that refers to anArrayListofStrings. - The right side of the assignment operator instantiates a new
ArrayListthat is empty (size of zero).
- The left side of the assignment operator declares a reference,
- We can display all the items in an
ArrayList<String>much like we did with arrays:public static void display(ArrayList<String> names, PrintStream out) { for(int i = 0; i < names.size(); ++i) { out.println(names.get(i)); } }- We can call
displayas follows:ArrayList<String> names = new ArrayList<>(); names.add("Peter"); names.add("Paul"); names.add("Mary-Anne"); display(names, System.out); // Note: System.out is a PrintStream object - The method will display all three names. If
nameshad twenty names in it, all twenty would be displayed.
- We can call
- It turns out that displaying the elements in an
ArrayListis actually much easier than this since thetoString()method for the class has been implemented to do this work for us. Instead of calling thedisplay()we wrote above, we can just say:out.println(names);
Examples
Consider the following two methods. Both of these methods reverse the order of the elements of an ArrayList<String>, and yet they are quite different.
public static ArrayList<Double> reverse1(ArrayList<Double> data) {
ArrayList<Double> temp = new ArrayList();
for(int i = data.size()-1; i >= 0; i--){
temp.add(data.get(i));
}
return temp;
}
public static ArrayList<Double> reverse2(ArrayList<Double> data) {
for(int i=0; i < data.size()/2; i++){
int j = data.size()-1-i;
Double temp = data.get(i);
data.set(i, data.get(j));
data.set(j, temp);
}
return data;
}
- Here we made use of the
Doublewrapper class instead ofdoublebecauseArrayLists cannot store primitive types. - Although these methods are doing the same thing as the methods with the same names in the array tutorial, the syntax is different because we now are sending messages to the
ArrayListobject instead of communicating directly with the array. - Do you see how these two methods differ in functionality?