JAVA - Zero to Hero / Collection Framework

Introduction to Collections

📚 Introduction to Collections in Java

In Java, a Collection is a framework that provides an architecture to store and manipulate a group of objects. It is part of the java.util package and includes interfaces, classes, and algorithms to perform various data structure operations efficiently.


🧩 Why Use Collections?

  • Arrays in Java have fixed size and are limited in functionality.

  • Collections provide dynamic resizing.

  • They come with built-in methods for searching, sorting, insertion, deletion, etc.

  • Collections help in writing clean, efficient, and reusable code.


🏗️ The Collection Hierarchy

The Collection Framework includes:

Each interface has different characteristics:

Interface

Description

Examples

List

Ordered collection, allows duplicates

ArrayList, LinkedList

Set

Unordered, no duplicates

HashSet, TreeSet

Queue

Ordered in a specific manner (FIFO, LIFO)

PriorityQueue, Deque

Map (not under Collection)

Stores key-value pairs

HashMap, TreeMap


🛠️ Common Collection Classes

Class

Description

ArrayList

Resizable array, fast access

LinkedList

Doubly-linked list, good for insertions/deletions

HashSet

Unordered set, no duplicates

TreeSet

Sorted set

HashMap

Key-value mapping, allows one null key

TreeMap

Sorted key-value pairs


⚙️ Basic Operations

All collections support common methods such as:

add()     // Adds an element
remove()  // Removes an element
size()    // Returns the number of elements
contains() // Checks for presence
clear()   // Removes all elements

🧠 Key Points

  • Collections work only with objects, not primitives.

  • Java 5 introduced generics to make collections type-safe (e.g., ArrayList<String>).

  • Collections can be iterated using loops or iterators.