allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œAct as if what you do makes a difference. It does.โ€
[William James (1842โ€“1910) โ€“ American philosopher and psychologist]


List and Set

15.1.1 What is a Collection?

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.


15.1.2 List Basics

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

java
import java.util.ArrayList; public class ListMiniLab { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); System.out.println("First name: " + names.get(0)); System.out.println("Total names: " + names.size()); for (String name : names) { System.out.println(name); } } }

Key points:

  • add() adds an element.

  • get(index) reads an element.

  • .size() returns how many elements.

  • You can loop with for-each.


15.1.3 Set Basics

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

java
import java.util.HashSet; public class SetMiniLab { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Apple"); // Duplicate - ignored System.out.println("Total fruits: " + fruits.size()); for (String fruit : fruits) { System.out.println(fruit); } } }

Key points:

  • Adding a duplicate does nothing.

  • No guarantee of order.

  • Fast checks: contains() tells you if an item exists.