Arrays and ArrayLists
Open in StudyFox Free, no ads. Practice, track progress and quiz yourself in the app.
AP Computer Science A · Lesson 5 of 6 · 9 min read
- Arrays have a fixed size:
int[] nums = new int[5]; Access with nums[i]; size is nums.length (no parentheses).
- ArrayLists resize:
ArrayList<String> list = new ArrayList<>(); Methods: add, get, set, remove, size().
- Enhanced for loop:
for (int n : nums) reads each element but can't change the array's contents or tell you the index.
- Removing while looping: when removing from an ArrayList, loop backward or don't increment after a removal, or you'll skip elements.
- Searching and sorting: linear search, binary search (sorted data only), selection sort, insertion sort, and merge sort (recursive).
// Remove all negative numbers
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i) < 0) {
list.remove(i);
}
}
Check your understanding
How do you get the number of elements in an array arr?
arr.size()arr.lengtharr.length()arr.count
Show answer
Answer: B. Arrays use the field length with no parentheses. ArrayLists use size(); Strings use length().