Generics Flashcards

1
Q
  1. Generic type declarations can be used as…
  2. What are the 4 possible constraints for these declarations?
A
  • Fields
  • Parameters
  • Local variables
  • Return types
  1. <Type>
  2. <?>
  3. <? extends Type>
  4. <? super Type>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. What are generics?
  2. Can a generic type be passed to another generic type?
A
  1. Generics are parameterized classes, interfaces, or methods
  2. Yes
MyGeneric<T> {...}

MyOtherGeneric<U> {...}

MyGeneric<MyOtherGeneric<SomeClass>>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. What is the syntax for a generic constructor?
  2. Is the generic constructor type parameter the same as its generic class parameter?
  3. Can a generic constructor be used inside a non-generic class?
A
  1. <T> ConstructorName(T param) {...}
  2. No
  3. Yes
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can a non-generic class be a superclass of a generic class?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. What is the syntax for a generic method?
  2. Is the generic method type parameter the same as its generic class parameter?
  3. Can a generic method be defined inside a non-generic class?
  4. Can a generic method be static or non-static?
A
<T> T method(T param) {...}

<T> ReturnType method(T param) {...}
  1. No
  2. Yes
  3. Yes
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the syntax for a generic class that implements a generic interface?

A
interface MyGenericInterface<T> {...}

class MyGenericClass<T> implements MyGenericInterface<T> {...}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
  1. When defining a generic class, what is the syntax to bind a generic type parameter to another class and interfaces?
A
  1. class MyGeneric<T extends ClassName & InterfaceName, InterfaceName2> {...}

ClassName must always be first

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

Legal or illegal?

class A {...}
class B {...}
class MyGeneric<T> {...}

MyGeneric<B> b = new MyGeneric<>();
MyGeneric<A> a = b;
A

Illegal. Even though B extends A, MyGeneric<A> has no relationship to MyGeneric<B>

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

What is type erasure?

A

Type erasure is the process whereby the Java compiler erases all of the generic type parameters and replaces them with Object if unbounded or with their bounded type if bounded

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

Legal or illegal?

MyGeneric<T>[] arr;

A

Illegal

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

Can a generic class define static parameterzed members?

A

No, but generic methods can be static

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