Generics
Generics are all about writing reusable code that can work with different data
types.
They help you avoid casting and provide compile-time type checking, which
reduces runtime errors.
To define a generic class, use the angle brackets <> after the
class name
Type erasure:
Type erasure is a concept in Java generics where generic type information is
removed at compile time and not retained at runtime
Wildcards:
Wildcards ( ? ) allow you to work with unknown types in a generic class or
method.
You can use wildcards when you want to keep the generic class flexible without
knowing the exact type.
Types
1. Upper Bounded Wildcards:
Use an upper-bounded wildcard ( <? extends T> ) when you want to read
values from a collection and ensure that they are of a certain type or its
subtypes.
You can restrict the types that can be used as generic parameters
2. Lower Bounded Wildcards:
Use a lower-bounded wildcard ( <? super T> ) when you want to add values
to a collection and ensure they are of a certain type or its supertypes.
3. Unbounded Wildcards ( <?> ):
Generics 1
Unbounded wildcards, represented by <?> , are the most flexible wildcards.
They allow any type, and they are useful when you don't care about the
specific type.
Type Arguments:
Type arguments are specific data types that you provide when using a generic
class or method. They replace the type parameters defined in the generic class
or method.
For example, in List<Integer> , Integer is the type argument, specifying that the
List will store and work with integers.
Type Parameter:
A type parameter is a placeholder or variable used in the definition of a generic
class or method
For example, in class Box<T> , T is the type parameter, which can be replaced
with a specific data type like Integer , String , etc., when you create an instance
of the Box class.
Bridge methods :
Bridge methods are used to maintain type safety and correctness during the
interaction between raw (non-generic) types and generic types.
Generics 2