Generics Flashcards
Why Java Generics?
Bugs that may appear at runtime (due to casts and then accessing illegal methods) can be detected at compile time.
Allows compile time checking of java types, removes requirement to cast objects.
What are the 3 types of generics?
Generic types
Generic methods
Generic constructors
A generic container is…
using a type variable conventionally a single uppercase letter i.e. public class Container { private T contents; public void add(T contents) { this.contents = contents; }
Container containedDouble; containedDouble = new Container();
Why use generic types?
You can reuse code with different types.
Common type parameter names
E - element K - key N - number T - type V - value S, U, V, etc - 2nd 3rd 4th types.
A generic method is…
A method with a type variable before the return variable i.e.
public static void genericMethod(S var){
}
MyClass object = new MyClass(); String a = object.genericMethod("Hello");
A generic constructor is…
public class MyClass{ MyClass(){ } }
What is a bounded type?
When you want a class/method to also exhibit certain properties you can make it extend a supertype or implement an interface i.e.
public void genericMethod(S input) means to legally compile the argument must be a number or subtype of it.
What is subtyping?
Double and Integer are subtypes of Number
Container and Container are NOT subtypes of Container
Container is a subtype of Container extends Number>
? is a known wildcard.
What is type erasure?
As generics were late to java, type erasure allows for backwards compatability. The compiler removes all type information from parameters and arguments within generic classes/methods. i.e. Spoon -> Spoon
What is heap pollution?
Heap pollution is the situation when a variable of a declared parameterised type refers to an instance that is not of that parameterised type.
i.e. List l = new ArrayList(); List ls = l;