Generics Flashcards
How do you define a generic class?
modifiers class class-name {T, X}
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?
Warning
public class Person{S, T} {
private S name; private T age; ... }
Suppose you have this class declaration, how do you instantiate it?
- Person person1 = new Person{String, String}(“Whiz”, 10);
- Person person2 = new Person<>(“Whiz”, 10); // Using diamond
- Person person3 = new Person(“Whiz”, 10);
How do you declare a bounded parameter?
Using the keyword extends on the generic parameter
public class X {U extends Number}
When are two generic classes considered superclass and subclass of each other?
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
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
Compilation fails at compile time. Because the upperbound of getVarT() is number and it cannot be assigned to Integer without a cast
In generics, what is a raw type?
A generic type without specifying its associated type
ex. Pair{Integer, String} worldCup = new Pair(2018, "Russia")
How do you declare a generic method?
public static {T} void fill(List {T} values, T val)