OSJava.011: Java Generics and Collections — Type Safety, Lists, Sets and Maps

Oil-painted conceptual illustration of ordered observations, unique components and paired records.

Open-Source Java Programming • Intermediate • Estimated study time: 45 minutes.

Generics allow classes, interfaces and methods to declare type parameters, enabling reusable code with compile-time type checks. The Java Collections Framework supplies common data structures through interfaces and implementations. The preceding interfaces and abstract classes lesson introduced programming against a contract; collections put that principle into practice.

Prerequisites and learning objectives

Install JDK 21 or a compatible newer release. Review arrays, methods and parameters and classes and objects. By completion, learners can declare parameterized collection types, choose an implementation through its interface, preserve ordered observations and duplicates in a list, identify unique elements with a set, and maintain keyed readings in a map while distinguishing zero from missing data. All measurements in the laboratory are synthetic.

Type parameters and type safety

The official Dev.java generics guide explains parameterized types. List<String> accepts string elements, and Map<String, Integer> associates string keys with boxed integer values. Primitive types such as int cannot directly serve as generic type arguments, so Integer supplies the corresponding reference type. Autoboxing converts int values to Integer where appropriate; unboxing a null Integer throws NullPointerException. The diamond operator infers constructor type arguments from context. Generic checks occur primarily at compile time, with most type arguments erased during compilation. Avoid raw collection types because they bypass useful checks.

Coding with John introduces Java generics and explains how type parameters support reusable, type-safe programs. Watch at source.

Selecting a collection by its contract

The List reference tutorial explains position-based access. ArrayList is a resizable array implementation; a List retains element order and permits duplicates. Indexed access is constant time for ArrayList, while insertion into the middle can require shifting elements. The Set tutorial describes collections that exclude duplicate elements. HashSet supplies hash-based membership checks without promising an iteration order. LinkedHashSet preserves insertion order, and TreeSet maintains sorted order according to its ordering rules.

A Map associates keys with values, with at most one value per key. Map is part of the framework but does not extend Collection. HashMap provides expected constant-time lookup and insertion under good hash distribution; it does not guarantee iteration order. LinkedHashMap can preserve encounter order, while TreeMap sorts keys and ordinarily provides logarithmic lookup and insertion. When a key already exists, put replaces its mapped value. Different keys may share a value. Use containsKey when absence matters, especially with maps permitting null values.

Telusko covers the Java Collections API beginning at 11:03:45, including ArrayList, Set and Map in successive sections. Watch the collections chapter at 11:03:45.

Laboratory: rack observations and keyed readings

The program records a synthetic sequence of rack visits, identifies unique rack identifiers, and stores the most recent integer temperature reading for each rack. Declare variables using List, Set and Map interfaces while constructing concrete ArrayList, HashSet and HashMap objects. Save the following complete program as Main.java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class Main {
    static void check(boolean condition, String name) {
        if (!condition) throw new AssertionError(name);
        System.out.println("PASS " + name);
    }
 
    public static void main(String[] args) {
        List<String> observations = new ArrayList<>();
        observations.add("R1");
        observations.add("R2");
        observations.add("R1");
        check(observations.equals(List.of("R1", "R2", "R1")),
              "list order and duplicates");
 
        Set<String> racks = new HashSet<>(observations);
        check(racks.equals(Set.of("R1", "R2")), "unique racks");
        check(!racks.add("R1"), "duplicate rejected");
 
        Map<String, Integer> readings = new HashMap<>();
        readings.put("R1", 24);
        readings.put("R2", 0);
        readings.put("R1", 30);
        check(readings.size() == 2 && readings.get("R1") == 30,
              "key replacement");
        check(readings.containsKey("R2") && readings.get("R2") == 0,
              "zero is present");
        check(!readings.containsKey("R3") && readings.get("R3") == null,
              "missing key");
    }
}

Compile with strict lint warnings enabled and execute the program using the following commands:

javac -Xlint:all -Werror Main.java
java Main

OpenJDK 21.0.12.1 compiled the program successfully and produced the following output:

PASS list order and duplicates
PASS unique racks
PASS duplicate rejected
PASS key replacement
PASS zero is present
PASS missing key

A deliberate compile-time error

The compiler protects a typed list against accidentally inserting incompatible values. Save the following intentionally invalid example in a separate file named Invalid.java:

import java.util.ArrayList;
import java.util.List;
class Invalid {
    void invalid() {
        List<String> names = new ArrayList<>();
        names.add(42);
    }
}

Run the following command to observe the expected compiler rejection:

javac Invalid.java

The actual test returned a nonzero exit status and reported that int cannot be converted to String. Keep the invalid example separate from Main.java. The rejection is the intended result, not a defect in the functioning laboratory.

Engineering interpretation and limitations

The list preserves a record of repeated visits, whereas the set removes duplicates using equality semantics. The map represents latest values rather than a historical series. In the laboratory, rack R2 has a legitimate zero reading; R3 has no entry. A real monitoring system would require timestamps, measurement units, validation and a defined retention policy. The sample collections are not synchronized for concurrent modification. Hash-based collections depend on consistent equals and hashCode implementations, so avoid changing fields used in hashing while an object is a key or set element. Choose ordered or concurrent alternatives when operational requirements demand them.

Exercises and answer key

Exercise 1: Add another R2 observation and predict the list size and unique rack count. Exercise 2: Explain why adding R1 to the set returns false. Exercise 3: Put another reading for R2 and predict the map size. Exercise 4: Explain why containsKey distinguishes an absent entry from a present null mapping in HashMap. Exercise 5: Explain why List<String> rejects an integer argument.

Answers: 1. If added before the set is constructed, the list contains four observations and the set contains two unique identifiers. 2. The element already exists, so the set does not change. 3. The value changes but the map still contains two keys. 4. get can return null for both cases, whereas containsKey detects an existing mapping. 5. The declared element type is String, and the compiler rejects an incompatible argument.

Conclusion

Generic collections combine reusable interfaces with type-safe data handling. Select lists for ordered sequences, sets for unique membership and maps for keyed associations. Test ordering, duplicate behavior, missing values and compile-time constraints separately. Choose an implementation according to the application rather than assuming every collection guarantees the same performance or ordering.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply