Lesson 14 of 20
ArrayList
ArrayList
ArrayList is a resizable array from java.util. Unlike a plain array, it grows automatically:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
System.out.println(list.size()); // 3
System.out.println(list.get(1)); // banana
System.out.println(list.contains("apple")); // true
list.remove("banana");
System.out.println(list.size()); // 2
System.out.println(list); // [apple, cherry]
Sorting
import java.util.Collections;
ArrayList<Integer> nums = new ArrayList<>();
nums.add(3); nums.add(1); nums.add(2);
Collections.sort(nums);
System.out.println(nums); // [1, 2, 3]
Iterating
for (String item : list) {
System.out.println(item);
}
Your Task
Create an ArrayList<String> with "banana", "apple", "cherry", "date". Then:
- Print its size
- Print the first element (
get(0)) - Print whether it contains "apple"
- Sort it with
Collections.sort, then print the whole list - Remove "cherry", print the new size, print the first element
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.