ECM2414 generics Flashcards
What is the purpose of Java generics?
Java generics add stability by detecting more bugs at compile time, enable code reuse with different inputs, and improve type safety by removing the need for casting.
When were generics introduced to Java?
Generics were added in Java 5.0.
What problem arises from using a generic Object container?
It requires manual casting, which can lead to runtime errors if incorrect types are used.
How are generic type parameters conventionally named?
Commonly used single, uppercase letters like:
T (Type) E (Element) K (Key) V (Value) N (Number)
What is a bounded type in Java generics?
A bounded type restricts the type parameters using extends (upper bound) or super (lower bound), e.g., <T>.</T>
What is type erasure in Java generics?
Type erasure removes all generic type information at compile time, ensuring backward compatibility with older versions of Java.
What are wildcard generics?
The ? wildcard represents an unknown type and is used for flexibility, e.g., Container<? extends Number>.
Why should you avoid mixing legacy and generic types?
Mixing them can cause unchecked warnings and defeat the purpose of generics by reintroducing potential runtime bugs.
What is heap pollution in Java generics?
Heap pollution occurs when a variable of a parameterized type refers to an object not of that type, potentially causing runtime errors.
What advantage do generics provide during compilation?
Generics enable the compiler to catch type-related errors, reducing runtime exceptions.