Generics Flashcards

1
Q

Why Java Generics?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the 3 types of generics?

A

Generic types
Generic methods
Generic constructors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

A generic container is…

A
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();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why use generic types?

A

You can reuse code with different types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Common type parameter names

A
E - element
K - key
N - number
T - type
V - value
S, U, V, etc - 2nd 3rd 4th types.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

A generic method is…

A

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");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

A generic constructor is…

A
public class MyClass{
        MyClass(){
        }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a bounded type?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is subtyping?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is type erasure?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is heap pollution?

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly