AlgoGalaxy

AlgoGalaxy

University
CodeRush
Jobs
Tools
Insights
Explore
Personalize
KotlinGoPHPRustGraphsArraysBit ManipulationDynamic ProgrammingGreedyHeapLinked ListStackStringsTreesTrieBacktrackingBinary SearchBSTComplexity AnalysisData Structures & Algorithms

Java | Generics

Generics move type mistakes from runtime to compile time. Parameterized collections, reusable methods and wildcard bounds let an API express what types it accepts, produces and safely transforms without raw casts.

Type Parameters

A type parameter such as T is a placeholder chosen by the caller. List means the collection is intended to contain strings, so inserting an Integer fails during compilation instead of later during a cast.

Generic Classes and Methods

A generic class stores one consistent type across its methods, while a generic method introduces a type parameter only for one operation. Both eliminate duplicated implementations that differ only by value type.

Invariance

List is not a List, even though Integer is a Number. If it were, code could insert a Double into a list promised to hold Integer values. Wildcards express safe variation instead.

PECS Wildcards

Producer Extends, Consumer Super: read numbers from List; write Integer values to List. A wildcard is a contract about the direction values safely move through an API.

Type Erasure

Most generic type information is erased at runtime for backward compatibility. You cannot create new T directly or overload methods that differ only by generic type arguments; design around factories and explicit Class values when needed.

Worked Examples

Example 1: Build a Type-Safe Box

The Box class is reusable for any type but each instance preserves its chosen type. No cast is required when getting a String from Box.

Code

public class Main {
    static class Box<T> {
        private final T value;

        Box(T value) {
            this.value = value;
        }

        T get() {
            return value;
        }
    }

    public static void main(String[] args) {
        Box<String> message = new Box<>("typed value");
        String result = message.get();
        System.out.println(result.toUpperCase());
    }
}

Expected Result

TYPED VALUE

Example 2: Write a Generic Swap Method

The method-level type parameter applies to one list operation. It works for a list of strings, integers or any reference type because the temporary variable keeps the same T as both list positions.

Code

import java.util.ArrayList;
import java.util.List;

public class Main {
    static <T> void swap(List<T> values, int first, int second) {
        T temporary = values.get(first);
        values.set(first, values.get(second));
        values.set(second, temporary);
    }

    public static void main(String[] args) {
        List<String> planets = new ArrayList<>(List.of("Mars", "Venus", "Earth"));
        swap(planets, 0, 2);
        System.out.println(planets);
    }
}

Expected Result

[Earth, Venus, Mars]

Example 3: Sum a Number Producer

The extends wildcard accepts List, List and other Number subtypes. The method only reads values, so it never needs to insert a value whose exact subtype is unknown.

Code

import java.util.List;

public class Main {
    static double sum(List<? extends Number> values) {
        double total = 0;
        for (Number value : values) {
            total += value.doubleValue();
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sum(List.of(2, 3, 5)));
        System.out.println(sum(List.of(1.5, 2.5)));
    }
}

Expected Result

10.0
4.0

Example 4: Copy Into an Integer Consumer

The super wildcard permits List, List and List destinations. The method writes Integer values safely, but it should not assume reads return anything more specific than Object.

Code

import java.util.ArrayList;
import java.util.List;

public class Main {
    static void addScores(List<? super Integer> destination) {
        destination.add(95);
        destination.add(88);
    }

    public static void main(String[] args) {
        List<Number> scores = new ArrayList<>();
        addScores(scores);
        Number first = scores.get(0);
        System.out.println(first.intValue() + scores.get(1).intValue());
    }
}

Expected Result

183

Example 5: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Generics";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA GENERICS

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 6: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Generics";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA GENERICS

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 7: Guard an empty boundary

A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static boolean accepted(String value) {
        return value != null && !value.isBlank();
    }

    public static void main(String[] args) {
        System.out.println(accepted("Java Generics"));
    }
}

Expected Result

true

Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.

Example 8: Keep the transformation pure

This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static int doubleValue(int value) { return value * 2; }

    public static void main(String[] args) {
        System.out.println(doubleValue(6));
    }
}

Expected Result

12

Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.

Example 9: Make a branch deliberate

Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        int score = 7;
        String result = score >= 5 ? "ready" : "review";
        System.out.println(result);
    }
}

Expected Result

ready

Try next: Change the boundary value by one and explain exactly which branch becomes active.

Example 10: Use a collection without hidden mutation

Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> lessons = List.of("Java Generics", "boundary");
        System.out.println(String.join(" | ", lessons));
    }
}

Expected Result

Java Generics | boundary

Try next: Add one more item and predict the derived result before executing the code.

Example 11: Return a named outcome

A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    record Outcome(String status, String lesson) {}

    public static void main(String[] args) {
        Outcome outcome = new Outcome("ready", "Java Generics");
        System.out.println(outcome.status());
    }
}

Expected Result

ready

Try next: Rename the outcome in your own words while preserving the same success and failure rule.

Example 12: Trace a small loop

Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int value : new int[] {1, 2, 3}) total += value;
        System.out.println(total);
    }
}

Expected Result

6

Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.

Example 13: Keep display at the edge

The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static String display(String value) { return "Lesson: " + value; }

    public static void main(String[] args) {
        System.out.println(display("Java Generics"));
    }
}

Expected Result

Lesson: Java Generics

Try next: Change only the display text and verify that the underlying rule and result stay unchanged.

Example 14: Test the closest boundary

A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static int quantity(int value) {
        if (value < 1) throw new IllegalArgumentException("quantity must be positive");
        return value;
    }

    public static void main(String[] args) {
        System.out.println(quantity(1));
    }
}

Expected Result

1

Try next: Try the lowest supported value and then one value just outside the accepted range.

Example 15: Write a tiny regression check

A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Java Generics.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String result = "Java Generics".toUpperCase();
        if (!result.equals("JAVA GENERICS")) throw new AssertionError("contract failed");
        System.out.println("contract holds");
    }
}

Expected Result

contract holds

Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.

Complexity Analysis

Operation Complexity Explanation
Generic get or set O(1) time Generics provide compile-time safety without changing indexed collection access cost.
Generic list swap O(1) time Two reads and two writes exchange fixed positions.
Number-list sum O(n) time, O(1) space Every input number is read once into a running total.

Common Mistakes

  • Using raw List or raw Box types and losing compiler checking for inserted values.
  • Assuming List can be assigned to List because Integer extends Number.
  • Using extends when an API must insert values, or super when an API must read a precise subtype.
  • Trying to instantiate new T or use instanceof List after type erasure.

Interview Checklist

  • Explain what each type parameter represents and who chooses the concrete type.
  • State the invariance rule before introducing a wildcard escape hatch.
  • Apply PECS by identifying whether an argument produces values or consumes them.
  • Mention type erasure when discussing runtime reflection, overloads or array creation.
logo of AlgoGalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

AlgoGalaxy University

University HomeTechnology LearningCoding ProblemsLearning ProgressCareer OpportunitiesTechnology InsightsUtilNexa ToolsAlgoGalaxy HomeContact Support

AlgoGalaxy CodeRush

CodeRush HomeProblem SetsProgress TrackerLearn TechnologyTechnology JobsEngineering InsightsDeveloper UtilitiesAlgoGalaxy HomePrivacy Policy
Privacy Policy

 • 

Terms of Service

Copyright © AlgoGalaxy 2026