Lesson Completion
Back to course

Generic Methods: Type-Safe Method Parameters

Advanced
15 minutes4.8Java

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: Generic methods declare their own type parameters (<T>) independent of the class.
  • Syntax: <T> ReturnType methodName(T param). The compiler infers types from arguments (no need to explicitly specify). Enables reusable algorithms like Collections.sort(), Arrays.asList(). Static methods can be generic even if the class isn't!

Think of adjustable wrench. One tool adapts to any nut size—you don't need a different wrench for each nut. Generic methods = adjustable tools for any type!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: The Universal Adapter

Generic method = universal power adapter that works in any country. Plug in, it adapts!


3. Technical Mastery (The "Deep Dive")

Generic Method Syntax

java
// <T> declares type parameter BEFORE return type public <T> void printArray(T[] array) { for (T element : array) { System.out.println(element); } } // Calling (type inferred) Integer[] nums = {1, 2, 3}; printArray(nums); // T inferred as Integer String[] words = {"A", "B"}; printArray(words); // T inferred as String

Type Inference

java
// Manual type specification (rarely needed) Box.<String>create("Hello"); // Automatic inference (preferred) Box.create("Hello"); // Compiler infers String

4. Interactive & Applied Code

java
import java.util.*; public class GenericMethodDemo { // Generic method: works with any type public static <T> void printArray(T[] array) { System.out.print("["); for (int i = 0; i < array.length; i++) { System.out.print(array[i]); if (i < array.length - 1) System.out.print(", "); } System.out.println("]"); } // Generic method: returns generic type public static <T> T getFirst(List<T> list) { if (list.isEmpty()) return null; return list.get(0); } // Multiple type parameters public static <K, V> void printPair(K key, V value) { System.out.println(key + " -> " + value); } // Generic method in NON-generic class public static <T> List<T> createList(T... elements) { List<T> list = new ArrayList<>(); for (T element : elements) { list.add(element); } return list; } // Generic static method (factory pattern) public static <T> Box<T> createBox(T content) { Box<T> box = new Box<>(); box.set(content); return box; } public static void main(String[] args) { // printArray with different types Integer[] intArray = {1, 2, 3, 4, 5}; String[] stringArray = {"A", "B", "C"}; printArray(intArray); // T = Integer printArray(stringArray); // T = String // getFirst List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); String first = getFirst(names); // Type inferred System.out.println("First: " + first); // Multiple parameters printPair("Age", 25); // K=String, V=Integer printPair(1, "First"); // K=Integer, V=String // Varargs generic method List<String> fruits = createList("Apple", "Banana", "Cherry"); System.out.println("Fruits: " + fruits); // Generic factory Box<Integer> intBox = createBox(42); System.out.println("Box content: " + intBox.get()); } } class Box<T> { private T content; public void set(T content) { this.content = content; } public T get() { return content; } }

5. The Comparison & Decision Layer

FeatureGeneric ClassGeneric Method
ScopeClass-levelMethod-level
Declarationclass Box<T><T> ReturnType method()
Type specifiedAt instantiationAt method call (inferred)
Static allowedNo generic staticsYes

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "What's the difference between a generic method and a method in a generic class?" Answer:

  • Generic METHOD: Declares own <T>, independent of class
  • Method in generic CLASS: Uses class's <T>
java
class Container<T> { // Generic class private T value; // Uses class's T public void set(T value) { this.value = value; } // Generic METHOD: own <U> independent of class <T> public <U> void print(U other) { System.out.println(value + " and " + other); } } Container<String> c = new Container<>(); c.set("Hello"); // T = String c.print(123); // U = Integer (different from T!)

Pro-Tip: Collections utility methods are great examples:

java
// All are generic static methods Collections.sort(list); // <T extends Comparable> Collections.max(list); // <T extends Comparable> Collections.reverse(list); // <T> Arrays.asList(1, 2, 3); // <T>

They work with ANY list type!

Topics Covered

Java FundamentalsAdvanced Java

Tags

#java#generics#type-safety#reusability

Last Updated

2025-02-01