# Week 6: Generics #### Objectives - Understand what generics are and why they are used - Learn how to define and use generic classes and methods - Explore built-in generic classes in Java - Implement a real-world use case using generics --- ### What are Generics? - Generics allow you to write flexible, reusable code that can operate on different types. - A feature that allows classes, interfaces, and methods to operate with types as parameters --- ### Why Use Generics? - **Type Safety**: Errors are caught at compile time, not runtime - **Elimination of Casting**: No need for explicit type casting - **Code Reusability**: Implement algorithms once, use with different types - **Performance**: No boxing/unboxing overhead for primitive types --- ### Writing a Generic Class #### Without Generics, With Generics ```java public class Box
{ private T content; public void setContent(T content) { this.content = content; } public T getContent() { return content; } } ``` ~.~ #### Generic Class Syntax - Use angle brackets `
` to denote type parameters - Convention: use single uppercase letters for type parameters - T (Type), E (Element), K (Key), V (Value), N (Number) ~.~ --- #### Built-in Generic Classes **List** ```java List
stringList = new ArrayList<>(); stringList.add("Hello"); String str = stringList.get(0); ``` **Map** ```java Map
map = new HashMap<>(); map.put(1, "One"); String value = map.get(1); ``` --- ### Advanced Concepts #### Bounded Type Parameters ```java public class NumberBox
{ private T number; public NumberBox(T number) { this.number = number; } public T getNumber() { return number; } } ``` --- #### Generic Methods, That Accept Generic Class Objects ```java public class Utility { public static
void printArray(T[] array) { for (T element : array) { System.out.println(element); } } } ``` --- #### Generic Interfaces ```java // Generic interface public interface Comparable
{ int compareTo(T other); } // Implementation of a generic interface public class Person implements Comparable
{ private String name; private int age; @Override public int compareTo(Person other) { return Integer.compare(this.age, other.age); } } ``` --- ### Type Erasure in Java Generics Type erasure is a process in Java where _generic type parameters are removed at compile-time_, meaning that generics _do not exist at runtime_. The compiler replaces the generic types with their _upper bound (or Object if no bound is specified)_ - The process by which the compiler removes generic type information during compilation - At runtime, generic types are replaced with their bounds or Object - The bytecode contains no information about generic types --- #### Example of Erasure ```java // During compilation: public class Box
{ private T value; public T get() { return value; } public void set(T value) { this.value = value; } } // After erasure (bytecode): public class Box { private Object value; public Object get() { return value; } public void set(Object value) { this.value = value; } } ``` #### Erasure with Bounded Types ```java // During compilation: public class NumericBox
{ private T value; public T get() { return value; } public void set(T value) { this.value = value; } } // After erasure (bytecode): public class NumericBox { private Number value; public Number get() { return value; } public void set(Number value) { this.value = value; } } ``` --- #### Consequences of Erasure - Cannot overload methods that would have the same erasure - Cannot create arrays of a generic type - Cannot use instanceof with generic types - Static fields are shared across all instances regardless of type parameter --- #### Cannot Use Primitive Types as Type Arguments ```java // Error: Cannot use primitive type int as type argument List
numbers; // Compile-time error // Use wrapper classes instead List
numbers = new ArrayList<>(); ``` --- #### Cannot Use static Fields of Type Parameters ```java public class Counter
{ // Error: Cannot make a static reference to the non-static type T private static T defaultValue; // Compile-time error // This is OK private static int count = 0; } ``` --- ### EXAM I