Array vs ArrayList
A Brew Bar order starts with one drink, then the customer adds a muffin, then removes it, then adds two more coffees. An array's length is fixed the moment it is created, so it copes badly. ArrayList is the everyday answer: an ordered list that grows and shrinks as you go.
The rule
Fixed size, use an array; growing size, use an ArrayList.
List<String> items = new ArrayList<>();
items.add("Latte"); // [Latte]
items.add("Muffin"); // [Latte, Muffin]
items.add(0, "Mocha"); // [Mocha, Latte, Muffin]
items.set(2, "Scone"); // [Mocha, Latte, Scone]
items.remove("Latte"); // [Mocha, Scone]
System.out.println(items.get(0)); // Mocha
System.out.println(items.size()); // 2
System.out.println(items); // [Mocha, Scone]Side by side:
| Array | ArrayList | |
|---|---|---|
| Size | fixed at creation | grows and shrinks |
| Read | arr[i] |
list.get(i) |
| Write | arr[i] = x |
list.set(i, x) |
| Length | arr.length |
list.size() |
| Holds primitives | yes, int[] |
no, uses wrappers: List<Integer> |
| Prints nicely | no | yes |
The <String> part is a generic type argument: it tells the compiler what the list holds. Adding a number to a List<String> is then a compile error rather than a surprise later. The <> on the right, called the diamond, lets Java repeat the type for you. Generics only accept reference types, so you write List<Integer>, not List<int>. Java converts between int and Integer automatically (autoboxing).
Declaring the variable as the interface List rather than ArrayList keeps your code flexible, since it only relies on what every list can do.
Two common catches:
removehas two versions. On aList<Integer>,remove(1)removes the element at index 1, not the value 1. To remove a value, pass an object:remove(Integer.valueOf(1)).List.of(...)is unchangeable. It is great for fixed data, but callingaddon it throws anUnsupportedOperationException. Wrap it,new ArrayList<>(List.of(...)), when you need to edit.
The shortcut
Ask "Will the number of items change after I create it?" No, and it is a fixed table such as seven weekdays: an array is fine. Yes, or unsure: List<Type> x = new ArrayList<>();.
Will it change?
Customers add and remove items, so yes.
Drills
Answer fast — trust the rule.
How do you get the number of elements in List<String> items?
List<Integer> cups = new ArrayList<>(List.of(5, 10, 15)); cups.remove(1); System.out.println(cups); prints what?
Why does List<int> counts = new ArrayList<>(); fail to compile?
What happens with List<String> menu = List.of("Latte", "Mocha"); menu.add("Tea");?
Remember
- Fixed size, use an array; growing size, use an ArrayList.
- Declare as
List<Type> x = new ArrayList<>();and useget,set,add,remove,size. - Traps:
remove(int)means index, andList.ofcannot be changed.
