ArrayLists are essential in Java for managing collections of data. Understanding their methods, like adding, removing, and accessing elements, is crucial for efficient programming. These skills are key in AP Computer Science A, helping you tackle real-world coding challenges.
-
add(element)
- Adds the specified element to the end of the ArrayList.
- Increases the size of the ArrayList by one.
- If the ArrayList reaches its capacity, it automatically resizes to accommodate new elements.
-
add(index, element)
- Inserts the specified element at the specified index in the ArrayList.
- Shifts the element currently at that index (if any) and any subsequent elements to the right.
- Throws an IndexOutOfBoundsException if the index is out of range (index < 0 || index > size).
-
remove(index)
- Removes the element at the specified index from the ArrayList.
- Shifts any subsequent elements to the left to fill the gap.
- Returns the element that was removed, allowing for further use or processing.
-
remove(element)
- Removes the first occurrence of the specified element from the ArrayList.
- Returns true if the element was successfully removed; otherwise, returns false.
- If the element is not found, the ArrayList remains unchanged.
-
get(index)
- Retrieves the element at the specified index without removing it.
- Throws an IndexOutOfBoundsException if the index is out of range.
- Useful for accessing elements in the ArrayList for reading or processing.
-
set(index, element)
- Replaces the element at the specified index with the specified element.
- Returns the element that was replaced, allowing for further use or processing.
- Throws an IndexOutOfBoundsException if the index is out of range.
-
size()
- Returns the number of elements currently in the ArrayList.
- Provides a way to determine how many items are stored without iterating through the list.
- Useful for conditional logic and loops that depend on the number of elements.
-
clear()
- Removes all elements from the ArrayList, resulting in an empty list.
- The size of the ArrayList becomes zero after this operation.
- Does not return any value; it simply empties the list.
-
isEmpty()
- Returns true if the ArrayList contains no elements; otherwise, returns false.
- Useful for checking if the list is empty before performing operations that require elements.
- Helps prevent errors that may arise from operating on an empty list.
-
contains(element)
- Returns true if the ArrayList contains the specified element; otherwise, returns false.
- Uses the equals method to determine if the element is present.
- Useful for checking membership before performing operations that depend on the presence of an element.