Generics Flashcards

1
Q

How do you define a generic class?

A

modifiers class class-name {T, X}

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

public class Person {

private S name;
private T age;
    ... }

Person person3 = new Person(“Whiz”, 10);

The line that instantiates produces an error or a warning?

A

Warning

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

public class Person{S, T} {

private S name;
private T age;
    ... }

Suppose you have this class declaration, how do you instantiate it?

A
  1. Person person1 = new Person{String, String}(“Whiz”, 10);
  2. Person person2 = new Person<>(“Whiz”, 10); // Using diamond
  3. Person person3 = new Person(“Whiz”, 10);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you declare a bounded parameter?

A

Using the keyword extends on the generic parameter

public class X {U extends Number}

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

When are two generic classes considered superclass and subclass of each other?

A

Its considered when their raw types are in the same inheritance chain and the type arguments are no different

Ex.
ArrayList is a subtype of List
ArrayList is unrelated to ArrayList or List

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

public class Data{T extends Number} {

private T var;
	public Data(T var){
		this.var = var;
	}
	T getVarT(){
		return var;
	}
}

What happens when the code is compiled and executed?

Integer input = 0;
Data data = new Data(input); // line 1
Integer output = data.getVarT(); // line 2
A

Compilation fails at compile time. Because the upperbound of getVarT() is number and it cannot be assigned to Integer without a cast

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

In generics, what is a raw type?

A

A generic type without specifying its associated type

ex.
Pair{Integer, String} worldCup = new Pair(2018, "Russia")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you declare a generic method?

A

public static {T} void fill(List {T} values, T val)

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