Why ArrayList? Arrays vs ArrayList
Part of: ArrayList
The Problem with Arrays A Java array has a fixed length set when you create it. Once you write int[] a = new int[5];, the array can hold exactly five elements forever. If you need a sixth, you must allocate a brand new, larger array and copy every element across. This makes arrays awkward whenever the amount of data is unknown until the program runs. Enter ArrayList An ArrayList is a resizable list provided by the Java library. It grows and shrinks automatically as you add and remove elements, so you never manage capacity yourself. It lives in java.util, so you import it: The <String is a type parameter : it tells the compiler this list holds String objects. This is called a generic type, written ArrayList<E where E is the element type. Key Differences - Size : arrays use .length (a field); ArrayList uses .size() (a method). - Resizing : arrays are fixed; ArrayList grows automatically. - Access : arrays use a[i]; ArrayList uses list.get(i) and list.set(i, val). - Element type : arrays hold primitives or objects; ArrayList holds objects only (more on autoboxing later). When to Use Which Use an array when the size is known and fixed, or when you store primitives for speed. Use an Arr
Challenge: Count the Lines