Generic Methods

Generic Methods A Generic Method defines a method that operates on objects of various types while providing compile-time type safety. These methods can be used inside generic and non-generic classes. Syntax public <T> void printArray(T[] array) { for (T element : array) { System.out.println(element); } } <T> before the return type indicates the method is generic. T is the type parameter used within the method. Example public class Main { public static <T> void display(T[] items) { for (T item : items) { System.out.print(item + " "); } System.out.println(); } public static void main(String[] args) { Integer[] intArray = {1, 2, 3}; String[] strArray = {"A", "B", "C"}; display(intArray); display(strArray); } } Bounded Type Parameters Generic methods can restrict the types they accept using bounds. ...

May 8, 2025 · 1 min · Rohan

Generic Class

Generic Class A Generic Class allows the definition of classes with a placeholder for a type, enabling reusability and type safety. The type is specified when the object is instantiated. Syntax class Box<T> { T item; void set(T item) { this.item = item; } T get() { return item; } } Usage public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(100); System.out.println("Integer Value: " + intBox.get()); Box<String> strBox = new Box<>(); strBox.set("Hello Generics"); System.out.println("String Value: " + strBox.get()); } } Multiple Type Parameters class Pair<K, V> { K key; V value; Pair(K key, V value) { this.key = key; this.value = value; } K getKey() { return key; } V getValue() { return value; } } Benefits Reduces code duplication Type-safe data structures Easier to debug and maintain 🔗 Related Notes Generics Fundamentals Generic Methods

May 8, 2025 · 1 min · Rohan

Generics Fundamentals

Generics Fundamentals Generics in Java provide a way to define classes, interfaces, and methods with a placeholder for types. They allow for type safety and code reusability without the need for casting. Why Generics? Type Safety: Compile-time checking prevents runtime ClassCastException. Code Reusability: One class or method works with different types. Eliminates Casting: Reduces boilerplate casting code. Example Without Generics ArrayList list = new ArrayList(); list.add("Hello"); String s = (String) list.get(0); // requires casting Example With Generics ArrayList<String> list = new ArrayList<>(); list.add("Hello"); String s = list.get(0); // no casting required Generic Syntax class Box<T> { T item; void set(T item) { this.item = item; } T get() { return item; } } Benefits Prevents runtime errors More readable and maintainable code Encourages clean APIs 🔗 Related Notes Generic Class Generic Methods Functional Interfaces

May 8, 2025 · 1 min · Rohan