Generics Flashcards Preview

Java8 > Generics > Flashcards

Flashcards in Generics Deck (5)
Loading flashcards...
1

What is mandatory in declaring formal parameter type in methods?

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

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

2

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

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

3

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

extends

eg..,

4

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

What happens here?

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

5

List< ? super IOException> exceptions = new ArrayList();
4: exceptions.add(new Exception());
5: exceptions.add(new IOException());
6: exceptions.add(new FileNotFoundException());

What happens here?

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.”