List and Set
In Java, a collection is a container for storing multiple elements together under one name.
Instead of creating ten variables like int a, b, c, d...
, you put them in a List, Set, or Map.
Collections are part of the Java Collections Framework (JCF) โ a powerful set of classes and interfaces to handle groups of data efficiently.
Why use collections?
You can add, remove, search, and loop through elements easily.
They help you manage dynamic data: the number of items can grow or shrink at runtime.
They come with powerful methods for sorting, filtering, and transforming data.
A List is an ordered collection.
It allows duplicates.
Elements have an index: first element is index 0.
Most common implementation: ArrayList
.
Example uses: a list of names, scores, tasks in order.
Mini Lab: Using ArrayList
Key points:
add()
adds an element.
get(index)
reads an element.
.size()
returns how many elements.
You can loop with for-each
.
A Set is an unordered collection that does not allow duplicates.
The most common implementation is HashSet
.
Sets are perfect for:
Keeping unique items.
Checking if something exists quickly.
Mini Lab: Using HashSet
Key points:
Adding a duplicate does nothing.
No guarantee of order.
Fast checks: contains()
tells you if an item exists.