Java for Beginners · Module 5: Data and Methods
🎯 When an Array Is Not Flexible Enough
An array has a fixed size. If you do not know how many marks, names or messages you will receive, you have to guess a size in advance. ArrayList solves this: it is a resizable list that grows as you add elements and shrinks as you remove them. It lives in java.util.
| Array | ArrayList | |
| Size | fixed when created | grows and shrinks automatically |
| Holds | primitives or objects | objects only (wrapper types such as Integer) |
| Length | a.length | list.size() |
| Read / write | a[i] | list.get(i) / list.set(i, x) |
| Add / remove | not possible | add, remove, clear |
| Import needed | no | import java.util.ArrayList; |
Figure 1: Array versus ArrayList.
1️⃣ Using an ArrayList
The type in angle brackets <String> says what the list holds. It is called a generic type, and it makes Java check that you add only Strings.
| Method | What it does |
add(x) | adds at the end |
add(i, x) | inserts at position i |
get(i) | reads element i |
set(i, x) | replaces element i |
remove(i) / remove(obj) | removes by position / by value |
size() | number of elements |
contains(x), indexOf(x) | search |
isEmpty(), clear() | test / empty the list |
Figure 2: The ArrayList methods you will use most.
Program 1: Add, read, change and remove
import java.util.ArrayList;
public class ListBasics {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ajay");
names.add("Rahul");
names.add("Priya");
System.out.println(names);
System.out.println("size = " + names.size());
System.out.println("get(1) = " + names.get(1));
names.add(1, "Sana");
System.out.println("after add(1, Sana): " + names);
names.set(0, "Ajay D");
names.remove("Rahul");
names.remove(0);
System.out.println("after set/remove: " + names);
System.out.println("contains Priya? " + names.contains("Priya"));
System.out.println("indexOf Priya = " + names.indexOf("Priya"));
System.out.println("isEmpty? " + names.isEmpty());
for (String n : names) {
System.out.println("Hello " + n);
}
names.clear();
System.out.println("after clear: " + names + ", size = " + names.size());
}
}
[Ajay, Rahul, Priya]
size = 3
get(1) = Rahul
after add(1, Sana): [Ajay, Sana, Rahul, Priya]
after set/remove: [Sana, Priya]
contains Priya? true
indexOf Priya = 1
isEmpty? false
Hello Sana
Hello Priya
after clear: [], size = 0
- Printing a list shows its contents in square brackets. No
Arrays.toStringis needed. add(1, "Sana")inserts at position 1 and shifts the later elements right.- After
set(0, "Ajay D"),remove("Rahul")andremove(0)(which removes “Ajay D” at position 0), the list is[Sana, Priya]. - The for-each loop (Lesson 19) works on lists exactly as it does on arrays.
- The empty angle brackets in
new ArrayList<>()mean “work out the type from the left side”.
2️⃣ Wrapper Classes
| Primitive | Wrapper class |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Figure 3: Every primitive has a wrapper class.
int 5Integer objectstored in the list
int 5list.add(5) and int x = list.get(0) just work.Figure 4: Autoboxing and unboxing.
A list cannot hold int, only Integer. Java converts automatically, so you rarely notice. Wrapper classes also carry useful tools such as limits and parsing methods.
import java.util.ArrayList;
import java.util.Collections;
public class Wrappers {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(70);
marks.add(95);
marks.add(82);
marks.add(61);
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("marks = " + marks + ", total = " + total);
System.out.println("max = " + Collections.max(marks) + ", min = " + Collections.min(marks));
Collections.sort(marks);
System.out.println("sorted = " + marks);
Collections.reverse(marks);
System.out.println("reversed = " + marks);
Integer boxed = 100;
int plain = boxed;
System.out.println("boxed = " + boxed + ", plain = " + plain);
System.out.println("Integer.MAX_VALUE = " + Integer.MAX_VALUE);
System.out.println("Integer.parseInt(\"42\") + 1 = " + (Integer.parseInt("42") + 1));
System.out.println("Integer.toBinaryString(10) = " + Integer.toBinaryString(10));
System.out.println("Double.parseDouble(\"2.5\") = " + Double.parseDouble("2.5"));
System.out.println("Character.isDigit('7') = " + Character.isDigit('7'));
}
}
marks = [70, 95, 82, 61], total = 308
max = 95, min = 61
sorted = [61, 70, 82, 95]
reversed = [95, 82, 70, 61]
boxed = 100, plain = 100
Integer.MAX_VALUE = 2147483647
Integer.parseInt(“42”) + 1 = 43
Integer.toBinaryString(10) = 1010
Double.parseDouble(“2.5”) = 2.5
Character.isDigit(‘7’) = true
marks.add(70)boxes the int into anInteger.for (int m : marks)unboxes each one.Collections(note the s) is a helper class withsort,reverse,max,minand more.- You have already used wrapper tools:
Integer.parseInt(Lesson 9),Integer.MAX_VALUE(Lesson 8) andCharacter.isDigit(Lesson 8).
3️⃣ Two Traps with Integer
import java.util.ArrayList;
public class RemoveTrap {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(1);
list.remove(1);
System.out.println("remove(1) -> " + list);
list.remove(Integer.valueOf(1));
System.out.println("remove(Integer.valueOf(1)) -> " + list);
Integer a = 127, b = 127;
Integer c = 1000, d = 1000;
System.out.println("127 == 127 : " + (a == b));
System.out.println("1000 == 1000 : " + (c == d));
System.out.println("1000 equals : " + c.equals(d));
}
}
remove(1) -> [10, 30, 1]
remove(Integer.valueOf(1)) -> [10, 30]
127 == 127 : true
1000 == 1000 : false
1000 equals : true
- remove(int) versus remove(Object): on a list of Integers,
remove(1)removes the element at index 1 (the 20), not the value 1. To remove the value, writeremove(Integer.valueOf(1)). - == on wrappers: Java caches small Integer objects (-128 to 127), so
127 == 127happens to be true. For 1000 two separate objects are created and==is false. This is the same lesson as Strings (Lesson 23): compare objects with equals().
4️⃣ Filtering and Converting
The next program uses removeIf with a short form n -> n % 3 == 0 (a lambda). Read it as “remove every n for which n % 3 == 0 is true”. Lambdas are an advanced topic you will meet later.
import java.util.ArrayList;
public class Filter {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 1; i <= 10; i++) nums.add(i);
ArrayList<Integer> evens = new ArrayList<>();
for (int n : nums) {
if (n % 2 == 0) evens.add(n);
}
System.out.println("evens = " + evens);
nums.removeIf(n -> n % 3 == 0);
System.out.println("without multiples of 3 = " + nums);
int[] arr = {5, 3, 8};
ArrayList<Integer> fromArray = new ArrayList<>();
for (int x : arr) fromArray.add(x);
Integer[] back = fromArray.toArray(new Integer[0]);
System.out.println("list = " + fromArray + ", array length = " + back.length);
}
}
evens = [2, 4, 6, 8, 10]
without multiples of 3 = [1, 2, 4, 5, 7, 8, 10]
list = [5, 3, 8], array length = 3
- To filter, loop and add the wanted items to a new list.
- Removing items while looping over the same list with for-each is not allowed (it fails at run time).
removeIfdoes it safely. - To move between an array and a list, copy with a loop, or use
toArray.
5️⃣ Errors Beginners Meet
Primitive type inside the brackets
import java.util.ArrayList;
public class Bad1 {
public static void main(String[] args) {
ArrayList<int> list = new ArrayList<>();
}
}
Bad1.java:5: error: unexpected type
ArrayList<int> list = new ArrayList<>();
^
required: reference
found: int
1 error
- Use the wrapper:
ArrayList<Integer>.
Forgetting the import
public class Bad2 {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ajay");
}
}
Bad2.java:3: error: cannot find symbol
ArrayList<String> names = new ArrayList<>();
^
symbol: class ArrayList
location: class Bad2
Bad2.java:3: error: cannot find symbol
ArrayList<String> names = new ArrayList<>();
^
symbol: class ArrayList
location: class Bad2
2 errors
- Add
import java.util.ArrayList;at the top (Lesson 10).
Mixing up array and list syntax
import java.util.ArrayList;
public class Bad3 {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add(5);
names.add("Ajay");
System.out.println(names.length());
System.out.println(names[0]);
System.out.println(names.get(3));
}
}
Bad3.java:6: error: incompatible types: int cannot be converted to String
names.add(5);
^
Bad3.java:8: error: cannot find symbol
System.out.println(names.length());
^
symbol: method length()
location: variable names of type ArrayList<String>
Bad3.java:9: error: array required, but ArrayList<String> found
System.out.println(names[0]);
^
3 errors
- A
Stringlist accepts only Strings. Usesize()instead oflength, andget(0)instead of[0].
An index that does not exist (runtime)
import java.util.ArrayList;
public class Idx {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ajay");
System.out.println(names.get(3));
}
}
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
… (internal lines)
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
ArrayList<int> | Primitives not allowed | ArrayList<Integer> |
list.length or list[0] | That is array syntax | list.size(), list.get(0) |
list.remove(1) on Integers | Removes index 1, not the value | remove(Integer.valueOf(1)) |
Comparing Integers with == | Works only for small cached values | Use equals() |
| Removing inside a for-each loop | ConcurrentModificationException | Use removeIf or an index loop |
| Forgetting the import | cannot find symbol | import java.util.ArrayList; |
❓ Frequently Asked Questions
Q1. Is ArrayList slower than an array?
Slightly, because of boxing and resizing. For most programs the difference does not matter.
Q2. How does it grow?
Internally it holds an array and creates a bigger one when full, copying the elements across. You never see this.
Q3. Can an ArrayList hold different types?
Only if declared as ArrayList<Object>, which is rarely a good idea. Normally a list holds one type.
Q4. What are the other collections?LinkedList, HashSet, HashMap and more. They are part of the Java Collections Framework, a natural next topic after this series.
✅ Key Takeaways
- ArrayList is a resizable list from
java.util:add,get,set,remove,size,contains. - It holds objects, so use wrappers:
ArrayList<Integer>, notArrayList<int>. - Autoboxing and unboxing convert between int and Integer automatically.
remove(int index)andremove(Object)are different: on an Integer list useInteger.valueOfto remove a value.- Compare wrapper objects with
equals(), not==. Collections.sort,max,minandreverseare ready-made helpers.
🎓 Practice questions: (1) Read numbers from the user until 0 and store them in an ArrayList; print the sum and average. (2) Remove all duplicate values from a list. (3) Explain whylist.remove(1)on anArrayList<Integer>may not do what you expect. (4) Sort a list of names alphabetically. (5) Write a method that takes anArrayList<Integer>and returns a new list of only its even numbers.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java