Unit 7 - ArrayLists
ArrayList vs. Array
- Functionally similar to arrays but with different commands.
- Offers additional features like dynamic resizing.
- Algorithms from one-dimensional arrays (Unit 6) can be adapted for ArrayLists.
- Choice between array and ArrayList depends on the specific requirements.
Arrays
- Fixed size and memory allocation upon creation.
- Values at individual indexes can be modified.
- Size remains constant unless the entire array is replaced.
ArrayList
Importing ArrayList Class
- Import required before declaration:
import java.util.ArrayList;
Creating ArrayList
- Syntax:
ArrayList<DataType> variableName = new ArrayList<>(); - Example:
ArrayList<String> myList = new ArrayList<>(); - Creates an empty ArrayList with an initial size of zero.
- Automatically resizes as needed.
Adding Objects to ArrayList
addmethod used to insert elements.
Version 1: Adding to the End
- Syntax:
listName.add(object); - Appends the object to the end of the ArrayList.
- Example:
myList.add("apple");
Version 2: Adding at a Specific Index
- Syntax:
listName.add(index, object); - Inserts the object at the specified index, shifting subsequent elements.
- Example:
myList.add(1, "tuna"); - Inserts "tuna" at index 1, shifting existing elements.
- The one-parameter version of
addreturnstrue, while the two-parameter version returns nothing (void).
Replacing Objects
setmethod replaces an object at a given index.- Syntax:
listName.set(index, object); - Example:
myList.set(1, "bass"); - Replaces the object at index 1 with "bass".
- Comparable to array assignment:
myArray[1] = newValue;
Removing Objects
removemethod removes an object at a specified index.- Syntax:
listName.remove(index); - Example:
myList.remove(1); - Removes the object at index 1, shifting subsequent elements to fill the gap.
- Returns the removed object.
- Removed object can be stored in a variable:
String removed = myList.remove(1); - Important Note: Removing an object causes renumbering of subsequent elements, which can lead to bugs if not carefully handled.
Index Considerations
- Adding: You can add an object to an existing index or to the index immediately after the last one.
- Removing: You can only remove objects from existing indexes.
Retrieving Values
getmethod retrieves the object at a specified index.- Syntax:
listName.get(index); - Example:
System.out.println(myList.get(0));String value = myList.get(0);
- Comparable to array access:
String value = myArray[0];
Limitations: Object Types Only
- ArrayLists can only hold objects, not primitive types directly.
- Example:
ArrayList<int> invalidList;// Invalid
Wrapper Classes
- Used to store primitive types in ArrayLists.
- Wrapper classes encapsulate primitive values as objects.
IntegerforintDoublefordouble
Usage of Wrapper Classes
- Example:
ArrayList<Integer> myNumbers = new ArrayList<>();
Auto-boxing and Unboxing
- Auto-boxing: Automatic conversion of a primitive type to its corresponding wrapper class.
- Auto-unboxing: Automatic conversion of a wrapper class object to its corresponding primitive type.
- Old way (manual):
Integer.valueOf(5)to wrap the primitive value 5 into an Integer object.myNumbers.get(0).intValue()to unwrap the Integer object back to anint.
- Modern way (auto-boxing/unboxing):
myNumbers.add(5);// Auto-boxingint num = myNumbers.get(0);// Auto-unboxing
- Note: Auto-boxing might not always work as expected; understanding manual wrapping/unwrapping is beneficial.
Printing ArrayLists
- Directly printing an ArrayList gives a readable output.
System.out.println(myList);- Arrays, when printed directly, produce gibberish.
Traversing ArrayLists
- Using loops to access each element.
For Loop
Arrays:
for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }ArrayLists:
for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }Key differences:
- Accessing length:
array.length(no parentheses) vs.list.size()(with parentheses). - Accessing elements:
array[i]vs.list.get(i).
- Accessing length:
String length:
string.length()(with parentheses).
For-Each Loop (Enhanced For Loop)
Syntax:
for (DataType element : collection) { // Code to process element }Example:
ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(3, 1, 8)); for (int temp : nums) { System.out.println(temp); }Explanation:
tempholds a copy of each value in the ArrayList.- Loop iterates once for each element.
Disadvantages:
- No index information; cannot determine the position within the ArrayList.
- Cannot modify the ArrayList elements directly, as
tempholds only a copy.
ArrayList Creation Techniques
Quick Hardcoding (Not Recommended for AP Test):
ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(3, 1, 8));Preferred Method for AP Test:
ArrayList<Integer> nums = new ArrayList<>(); nums.add(3); nums.add(1); nums.add(8);
Important Considerations for Loops
- When using the
get,setandremovemethods you can only access existing indices. - When using the
addmethod, you can add one past the last index. - Adding or Removing Objects During Traversal:
- Can cause elements to shift, leading to skipped or double-accessed elements.
Algorithm: Removing Items from an ArrayList
Method Signature
public void removeItem(String itemToRemove)- Modifies the
itemsfield (ArrayList of String) in theShoppingListclass. - Does not return a value (void).
Traversal Order
Traverse the ArrayList from the end to the beginning to avoid skipping elements after removal.
for (int i = items.size() - 1; i >= 0; i--) { ... }
String Comparison
Use
.equals()method to compare strings, which accounts for capitalization.Use
.equalsIgnoreCase()to ignore capitalization.if (items.get(i).equals(itemToRemove)) { items.remove(i); }
Variations of the Algorithm
1. Returning the Count of Removed Items (int return type)
```java
public int removeItem(String itemToRemove) {
int count = 0;
for (int i = items.size() - 1; i >= 0; i--) {
if (items.get(i).equals(itemToRemove)) {
items.remove(i);
count++;
}
}
return count;
}
```
2. Searching for Partial Matches (using .contains() or .indexOf())
```java
if (items.get(i).contains(itemToRemove)) {
items.remove(i);
}
```
```java
if (items.get(i).indexOf(itemToRemove) != -1) {
items.remove(i);
}
```
3. Returning an ArrayList of Removed Items (ArrayList return type)
```java
public ArrayList<String> removeItem(String itemToRemove) {
ArrayList<String> removedItems = new ArrayList<>();
for (int i = items.size() - 1; i >= 0; i--) {
if (items.get(i).equals(itemToRemove)) {
String tempRemoved = items.remove(i);
removedItems.add(tempRemoved);
}
}
return removedItems;
}
```
Copying Arrays to ArrayLists
Steps
- Import
java.util.ArrayList. - Create an
ArrayListof the appropriate wrapper class type. - Use a for-each loop to traverse the array and add each element to the
ArrayList.
Example
int[] array = {5, 10, 15, 20, 25, 30};
ArrayList<Integer> arrayList = new ArrayList<>();
for (int temp : array) {
arrayList.add(temp);
}
System.out.println(arrayList);
Notes
ArrayListcan be directly printed usingSystem.out.println(), unlike arrays.- The wrapper class for
intisInteger.