Why collections, not arrays?
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop gets 5 orders today and 500 tomorrow. An array needs its size fixed in advance, so adding and removing orders quickly becomes painful.
Arrays have a fixed size
An array's size is fixed when you create it. In an online store, new String[3] has room for exactly three orders, forever, so a fourth order cannot fit.
Example 1 · An array cannot take one more student
public class FixedSizeDemo { public static void main(String[] args) { String[] students = new String[3]; students[0] = "Aarav"; students[1] = "Priya"; students[2] = "Rohan"; System.out.println("Seats in the array: " + students.length);
students[3] = "Kavya"; // a late admission System.out.println("Kavya added"); }}Seats in the array: 3 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at FixedSizeDemo.main(FixedSizeDemo.java:9)
What this code does
- The array was made with room for 3 names. Index
3would be a fourth slot, and that slot does not exist. - The program stops on line 9, so
Kavya addednever prints. The same array can never grow; you would have to build a new one.
Example 2 · Growing an array by hand
import java.util.Arrays;
public class GrowArrayDemo { static String[] addStudent(String[] old, String name) { String[] bigger = new String[old.length + 1]; for (int i = 0; i < old.length; i++) { bigger[i] = old[i]; } bigger[old.length] = name; return bigger; }
public static void main(String[] args) { String[] students = {"Aarav", "Priya", "Rohan"}; students = addStudent(students, "Kavya"); students = addStudent(students, "Arjun"); System.out.println(Arrays.toString(students)); System.out.println("Count: " + students.length); }}[Aarav, Priya, Rohan, Kavya, Arjun] Count: 5
What this code does
- Each call builds a brand-new array one slot bigger, copies every old name into it, and puts the new name in the last slot. The old array is thrown away.
- It works, but it is slow and easy to get wrong. Adding 1,000 students this way copies names about 5 lakh times.
Real data is not like that. Students join late, orders keep coming, a WhatsApp group keeps adding people. With an array you must guess the size in advance. Too small, and the program crashes with ArrayIndexOutOfBoundsException. Too big, and you waste memory and must track how many slots are really used.
The only way to "grow" an array is to create a new, bigger array and copy every item into it yourself.
Order of execution
Grow an array by hand
A full array of 3 orders must take a fourth. Put the steps in the order the code runs them.
No helpers: search, insert and remove by hand
Arrays have no remove and no contains. To answer "is Priya in the list?", you write a loop yourself, and the same small loop gets copied into every program.
String[] names = {"Asha", "Priya", "Ravi"};int position = -1;for (int i = 0; i < names.length; i++) { if (names[i].equals("Priya")) { position = i; }}System.out.println(position); // 1, after a hand-written loopSystem.out.println(names); // something like [Ljava.lang.String;@1b6d3586System.out.println(arr) prints something like [I@1b6d3586, not the items, and each hand-written copy of a loop is one more chance for an off-by-one bug.
Removing the second name out of five means moving every later name one step left; inserting at the front means moving them all right. You also need a separate count variable, because length is the room, not the number of items. One forgotten count-- and the data is wrong.
Example 3 · Removing from the middle: shift and count
import java.util.Arrays;
public class RemoveShiftDemo { public static void main(String[] args) { String[] pending = new String[5]; int count = 4; pending[0] = "Laptop"; pending[1] = "Mouse"; pending[2] = "Keyboard"; pending[3] = "Monitor";
int removeAt = 1; // the Mouse order was cancelled for (int i = removeAt; i < count - 1; i++) { pending[i] = pending[i + 1]; // move each later order one step left } count--; pending[count] = null; // clear the old last slot
System.out.println("Still pending: " + count); System.out.println(Arrays.toString(pending)); }}Still pending: 3 [Laptop, Keyboard, Monitor, null, null]
What this code does
pending.lengthis always 5. The real number of orders lives in a separatecountvariable, and we must keep it correct ourselves.- To remove the Mouse order, every later order moves one step left, then the old last slot is cleared. The
nulls at the end are unused room.
What is a collection?
A collection is an object that holds a group of other objects and can grow and shrink, like a list of orders. It comes with ready methods to add, remove and search.
A collection holds a group of objects and grows and shrinks by itself. ArrayList is the most used one: add makes room, remove closes the gap, and contains, indexOf and size() answer in one call.
Example 4 · The same jobs with ArrayList
import java.util.ArrayList;
public class ArrayListPreviewDemo { public static void main(String[] args) { ArrayList<String> pending = new ArrayList<>(); pending.add("Laptop"); pending.add("Mouse"); pending.add("Keyboard"); pending.add("Monitor"); pending.add("Webcam"); // no size limit
pending.remove("Mouse"); // the gap closes by itself System.out.println("Still pending: " + pending.size()); System.out.println(pending);
System.out.println("Is Keyboard pending? " + pending.contains("Keyboard")); System.out.println("Keyboard's position: " + pending.indexOf("Keyboard")); System.out.println("Is Mouse pending? " + pending.contains("Mouse")); }}Still pending: 4 [Laptop, Keyboard, Monitor, Webcam] Is Keyboard pending? true Keyboard's position: 1 Is Mouse pending? false
What this code does
addputs each order at the end, and the list makes room by itself.size()always gives the real count, so there is nocountvariable to manage.remove,containsandindexOfreplace three hand-written loops. Printing the list shows its items in order.
Printing a list shows its items directly, like [Laptop, Keyboard]. The Lists module covers ArrayList in full.
The Collections Framework
The Java Collections Framework is the family of ready interfaces and classes in the java.util package for storing groups of objects. A framework here means types made to work together, with the same method names everywhere.
The framework lives in java.util. Its collections are generic, like your Box<T> from the Generics module: ArrayList<String> holds only Strings, and the compiler checks it.
Example 5 · Numbers go in as Integer objects
import java.util.ArrayList;
public class MarksListDemo { public static void main(String[] args) { ArrayList<Integer> marks = new ArrayList<>(); marks.add(78); // autoboxing: int 78 becomes an Integer object marks.add(91); marks.add(64); marks.add(85);
int total = 0; for (int m : marks) { // unboxing: each Integer becomes an int total = total + m; } System.out.println("Marks: " + marks); System.out.println("Subjects: " + marks.size()); System.out.println("Total: " + total); System.out.println("Average: " + (double) total / marks.size()); }}Marks: [78, 91, 64, 85] Subjects: 4 Total: 318 Average: 79.5
What this code does
- The type inside the angle brackets must be a class, so whole numbers use the wrapper class
Integer. WritingArrayList<int>is a compile error. - Autoboxing turns
78into anIntegerobject when you add it. Unboxing turns it back into anintin the loop, so the maths looks normal.
Predict the output
Predict the output
Read each snippet and pick what it prints.
Round 1 of 2
ArrayList<Integer>, not ArrayList<int>. Autoboxing turns 87 into an Integer for you.When an array is still the right choice
Arrays are the right tool when the size is truly fixed and known: 12 months, 7 days, marks in exactly 5 subjects, a 3x3 board.
int[] daysInMonth = new int[12]; // always 12 monthsdouble[] subjectMarks = new double[5]; // exactly 5 subjectschar[][] board = new char[3][3]; // a 3x3 boardList<String> students = new ArrayList<>(); // size not known: a collectionArrays also store primitives like int directly, without wrapper objects, so they use less memory for large amounts of numbers. Many collections, including ArrayList, keep an array inside and manage it for you.
- Size: an array is fixed; a collection grows and shrinks.
- Element type: an array holds primitives or objects; a collection holds objects only.
- Helpers: an array has only
length; a collection hasadd,remove,contains,size()and more. - Printing: an array needs
Arrays.toString; a collection prints its items directly.
The first three lines have a size that never changes, so arrays fit. The last line has no known size, so it is a collection.
Next step
Check your understanding
11 quick questions