Generics Flashcards

1
Q

What is mandatory in declaring formal parameter type in methods?

A

It must be specified immediately before the return type of the method.

public static T identity(T t){ return t;}

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

What is interesting about Upper bounds and unbounded wild card? Why?

A

The list which is being used becomes logically immutable.

For example: List < ? extends Birds> list= new ArrayList();
The list can contain any birds. A sparrow, a pigeon anything as they exyends Bird.

So when we add list.add(new sparrow()), java doesnt accept as it is supposed to not work because of generics

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

What keyword we use on using upperbound wild card to interfaces?

A

extends

eg..,

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

List< ? > list = new ArrayList < ? extends A>();

What happens here?

A

The code will not compile. Because, We need to know what type of object when instantiating an arrayList. Here it could be anything that extends A, so it is not at all useful

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

List< ? super IOException> exceptions = new ArrayList();

4: exceptions.add(new Exception());
5: exceptions.add(new IOException());
6: exceptions.add(new FileNotFoundException());

What happens here?

A

Line 3 references a List that could be List or List or
List. Line 4 does not compile because we could have a List and
an Exception object wouldn’t fit in there.
Line 4 is fine. IOException can be added to any of those types. Line 5 is also fine. File-
NotFoundException can also be added to any of those three types. This is tricky because
FileNotFoundException is a subclass of IOException and the keyword says super. What
happens is that Java says “Well, FileNotFoundException also happens to be an IOException,
so everything is fine.”

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