12.8 Arrays versus ArrayLists
Table 12.1 summarizes the differences between arrays and ArrayLists.
Table 12.1 Summary of Arrays versus ArrayLists
Arrays | ArrayList | |
Construct support | Built into the language. | Provided by the generic class ArrayList<E>. |
Initial length/size specification | Length is specified in the array construction expression directly or indirectly by the initialization block. | Cannot specify the size at construction time. However, initial capacity can be specified. |
Length/size | The length of an array is static (fixed) once it is created. Each array has a public final int field called length. (The String and the StringBuilder class provide the method length() for this purpose.) | Both size and capacity can change dynamically. ArrayList<E> provides the method size() to obtain the current size of the list. |
Element type | Primitive and reference types. | Only reference types. |
Operations on elements | An element in the array is designated by the array name and an index using the [] operator, and can be used as a simple variable. | The ArrayList<E> class provides various methods to add, insert, replace, retrieve, and remove elements from a list. |
Iterator | Arrays do not provide an iterator, apart from using the for(:) loop for traversal. | The ArrayList<E> class provides customized iterators for lists, in addition to the for(:) loop for iterating over the elements (§15.2, p. 791). |
Generics | Cannot create arrays of generic types using the new operator. Runtime check required for storage at runtime. | ArrayList<E> is a generic type. Can create parameterized ArrayLists of reference types using the new operator. No runtime check required for storage at runtime, as type-safety is checked at compile time. |
Subtype relationship | Subtype relationship between two reference types implies subtype relationship between arrays of the two types—that is, element subtype relationship implies array subtype relationship. | Subtype relationship between two reference types does not imply covariance relationship between ArrayLists of the two types—that is, element subtype relationship does not imply list subtype relationship. |
Sorting | java.util.Arrays.sort(array) java.util.Arrays.sort(array), comparator) (§15.12, p. 864) | java.util.Collections.sort(list) java.util.Collections.sort(list, comparator) java.util.List.sort(comparator) (§15.11, p. 856) |
Text representation | java.util.Arrays.toString(array) | list.toString() |
Example 12.1 is a collection of code snippets used throughout this chapter to illustrate the various methods of the ArrayList<E> class.
Example 12.1 Using an ArrayList
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
public class ArrayListMethods {
public static void main(String[] args) {
String[] wordArray = { “level”, “Ada”, “kayak”, “Bob”, “Rotator”, “Bob” };
out.println(“(1) Create an empty list of strings:”);
List<String> strList = new ArrayList<>();
printListWithIndex(strList);
out.println(“\n(2) Add elements to list:”);
for (String str : wordArray) {
strList.add(str);
printListWithIndex(strList);
}
out.println(“Insert an element at index 2 in the list:”);
strList.add(2, “Java”);
printListWithIndex(strList);
out.println(“\n(3) Replace the element at index 1:”);
String oldElement = strList.set(1, “Naan”);
out.println(“Element that was replaced: ” + oldElement);
printListWithIndex(strList);
out.println(“\n(4) Remove the element at index 0:”);
out.println(“Element removed: ” + strList.remove(0));
printListWithIndex(strList);
out.println(“\n(5) Remove the first occurrence of \”Java\”:”);
out.println(“Element removed: ” + strList.remove(“Java”));
printListWithIndex(strList);
out.println(“\n(6) Determine the size of the list:”);
out.println(“The size of the list is ” + strList.size());
out.println(“\n(7) Determine if the list is empty:”);
boolean result = strList.isEmpty();
out.println(“The list ” + (result ? “is” : “is not”) + ” empty.”);
out.println(“\n(8) Get the element at specific index:”);
out.println(“First element: ” + strList.get(0));
out.println(“Last element: ” + strList.get(strList.size() – 1));
out.println(“\n(9) Compare two lists:”);
List<String> strList2 = new ArrayList<>(strList);
boolean trueOrFalse = strList.equals(strList2);
out.println(“The lists strList and strList2 are”
+ (trueOrFalse ? “” : ” not”) + ” equal.”);
strList2.add(null);
printListWithIndex(strList2);
trueOrFalse = strList.equals(strList2);
out.println(“The lists strList and strList2 are”
+ (trueOrFalse ? “” : ” not”) + ” equal.”);
out.println(“\n(10) Sublists as views:”);
out.println(“Underlying list: ” + strList); // [Naan, kayak, Bob, Rotator, Bob]
List<String> strList3 = strList.subList(1, 4);
out.println(“Sublist before remove: ” + strList3); // [kayak, Bob, Rotator]
out.println(“Remove: ” + strList3.get(0)); // “kayak”
strList3.remove(0); // Remove element at index 0
out.println(“Sublist after remove: ” + strList3); // [Bob, Rotator]
out.println(“Underlying list: ” + strList); // [Naan, Bob, Rotator, Bob]
out.println(“\n(11) Membership test:”);
boolean found = strList.contains(“Naan”);
String msg = found ? “contains” : “does not contain”;
out.println(“The list ” + msg + ” the string \”Naan\”.”);
out.println(“\n(12) Find the index of an element:”);
int pos = strList.indexOf(“Bob”);
out.println(“The index of string \”Bob\” is: ” + pos);
pos = strList.indexOf(“BOB”);
out.println(“The index of string \”BOB\” is: ” + pos);
pos = strList.lastIndexOf(“Bob”);
out.println(“The last index of string \”Bob\” is: ” + pos);
printListWithIndex(strList);
out.println(“\n(13) Iterating over the list using the for(;;) loop:”);
for (int i = 0; i < strList.size(); i++) {
out.print(i + “:” + strList.get(i) + ” “);
}
out.println();
out.println(“\n(14) Iterating over the list using the for(:) loop:”);
for (String str : strList) {
out.print(str + ” “);
// strList.remove(str); // Throws ConcurrentModificationException.
}
out.println();
out.println(“\n(15) Convert list to array:”);
Object[] objArray = strList.toArray();
out.println(“Object[] length: ” + objArray.length);
out.print(“Length of each string in the Object array: “);
for (Object obj : objArray) {
String str = (String) obj; // Cast required.
out.print(str.length() + ” “);
}
out.println();
String[] strArray = strList.toArray(new String[0]);
out.println(“String[] length: ” + strArray.length);
out.print(“Length of each string in the String array: “);
for (String str : strArray) {
out.print(str.length() + ” “);
}
}
/**
* Print the elements of a list, together with their index:
* [0:value0, 1:value1, …]
* @param list List to print with index
*/
public static <E> void printListWithIndex(List<E> list) { // (16)
List<String> newList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
newList.add(i + “:” + list.get(i));
}
out.println(newList);
}
}
Output from the program:
(1) Create an empty list of strings:
[]
(2) Add elements to list:
[0:level]
[0:level, 1:Ada]
[0:level, 1:Ada, 2:kayak]
[0:level, 1:Ada, 2:kayak, 3:Bob]
[0:level, 1:Ada, 2:kayak, 3:Bob, 4:Rotator]
[0:level, 1:Ada, 2:kayak, 3:Bob, 4:Rotator, 5:Bob]
Insert an element at index 2 in the list:
[0:level, 1:Ada, 2:Java, 3:kayak, 4:Bob, 5:Rotator, 6:Bob]
(3) Replace the element at index 1:
Element that was replaced: Ada
[0:level, 1:Naan, 2:Java, 3:kayak, 4:Bob, 5:Rotator, 6:Bob]
(4) Remove the element at index 0:
Element removed: level
[0:Naan, 1:Java, 2:kayak, 3:Bob, 4:Rotator, 5:Bob]
(5) Remove the first occurrence of “Java”:
Element removed: true
[0:Naan, 1:kayak, 2:Bob, 3:Rotator, 4:Bob]
(6) Determine the size of the list:
The size of the list is 5
(7) Determine if the list is empty:
The list is not empty.
(8) Get the element at specific index:
First element: Naan
Last element: Bob
(9) Compare two lists:
The lists strList and strList2 are equal.
[0:Naan, 1:kayak, 2:Bob, 3:Rotator, 4:Bob, 5:null]
The lists strList and strList2 are not equal.
(10) Sublists as views:
Underlying list: [Naan, kayak, Bob, Rotator, Bob]
Sublist before remove: [kayak, Bob, Rotator]
Remove: kayak
Sublist after remove: [Bob, Rotator]
Underlying list: [Naan, Bob, Rotator, Bob]
(11) Membership test:
The list contains the string “Naan”.
(12) Find the index of an element:
The index of string “Bob” is: 1
The index of string “BOB” is: -1
The last index of string “Bob” is: 3
[0:Naan, 1:Bob, 2:Rotator, 3:Bob]
(13) Iterating over the list using the for(;;) loop:
0:Naan 1:Bob 2:Rotator 3:Bob
(14) Iterating over the list using the for(:) loop:
Naan Bob Rotator Bob
(15) Convert list to array:
Object[] length: 4
Length of each string in the Object array: 4 3 7 3
String[] length: 4
Length of each string in the String array: 4 3 7 3
Leave a Reply