When you start learning Java, these topics come up everywhere — collections, ArrayList, wrapper classes, and memory. Instead of memorizing definitions, it’s better to understand how they actually work together.
Java Collections – The Big Picture
In Java, the Collection framework is used to store and manage groups of data.
Think of it like a toolbox. Inside it, you have different tools depending on your need.
Here’s a simple structure:
Collection (Interface)
|
|--- List
| |--- ArrayList
| |--- LinkedList
| |--- Vector
|
|--- Set
|--- HashSet
|--- LinkedHashSet
|--- TreeSet
- List → ordered, allows duplicates
- Set → no duplicates
What is ArrayList?
ArrayList is one of the most commonly used classes in Java.
It works like a dynamic array — meaning:
- You don’t need to fix the size
- It grows automatically when you add elements
Why developers like ArrayList:
- Maintains insertion order
- Allows duplicates
- Fast access using index
Example:
import java.util.*;
class Demo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(10);
System.out.println(list);
}
}
Output:
[10, 20, 10]
So yes — duplicates are allowed, and order is preserved.
Wrapper Class – Why Do We Need It?
Java has primitive types like:
int, char, double, boolean
But collections (like ArrayList) only store objects, not primitives.
That’s where wrapper classes come in.
| Primitive | Wrapper Class |
|---|---|
| int | Integer |
| char | Character |
| double | Double |
| boolean | Boolean |
Example:
int a = 10;
Integer obj = a; // Autoboxing
Java automatically converts int → Integer. This is called autoboxing.
Printing Wrapper Objects
Integer obj = 100;
System.out.println(obj);
Output:
100
You might expect a memory address, but you get the value.
Why?
Because wrapper classes override the toString() method — so they print the actual value.
Stack vs Heap – Simple Understanding
This is where many beginners get confused. Keep it simple:
Stack
- Stores primitive values
- Stores references (addresses) of objects
- Fast memory
Heap
- Stores actual objects
- Shared memory
Quick Table:
| Type | Stack | Heap |
|---|---|---|
| int (primitive) | Stored directly | ❌ |
| Integer | Reference stored | Object stored |
| ArrayList | Reference stored | Object stored |
Example to understand:
int a = 10;
Integer obj = new Integer(20);
-
a→ stored in stack -
obj→ reference in stack, actual object in heap
Top comments (0)