DEV Community

Cover image for Java Collections, ArrayList, Wrapper Class & Memory Management (Stack vs Heap)
Vidya
Vidya

Posted on

Java Collections, ArrayList, Wrapper Class & Memory Management (Stack vs Heap)

Java Collections Hierarchy (Image Format)

              Collection (Interface)
                        |
        ---------------------------------
        |                               |
     List (Interface)               Set (Interface)
        |                               |
   ------------------          ---------------------
   |        |       |          |        |         |
ArrayList LinkedList Vector   HashSet LinkedHashSet TreeSet
  (Class)    (Class) (Class)   (Class)   (Class)    (Class)

Enter fullscreen mode Exit fullscreen mode

What is ArrayList?
ArrayList is a class in Java that implements the List interface and is part of the Collection framework. It uses a dynamic array, meaning its size can grow or shrink automatically when elements are added or removed. ArrayList maintains the insertion order and allows duplicate elements. It is widely used because it provides fast access to elements using index positions.
Examples

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

[10, 20, 10]

What is Wrapper Class?
A wrapper class converts primitive data types → objects.

Examples:


       Primitive        Wrapper Class
       int              Integer
       char             Character
       double               Double
       boolean              Boolean


Enter fullscreen mode Exit fullscreen mode

Example:
int a = 10;
Integer obj = a; // Autoboxing

What happens when we print Wrapper Class?
Integer obj = 100;
System.out.println(obj);
Output:
--> 100
Internally:
--> Wrapper class overrides toString()
--> So it prints value, not memory address

Stack vs Heap


┌─────────────────────┬────────────────────────┬────────────────────────┐
│  Type                 Stored in Stack          Stored in Heap      │
├─────────────────────┼────────────────────────┼────────────────────────┤
│   Primitive (int)      Yes                       No                 │
├─────────────────────┼────────────────────────┼────────────────────────┤
│   Wrapper Object       Reference only           Object             │
├─────────────────────┼────────────────────────┼────────────────────────┤
│   ArrayList           Reference only            Object             │
└─────────────────────┴────────────────────────┴────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Top comments (0)