Explicit Java Generation

Why T

can't generic be used as a return type class

if T extends Class

.

Example:

public class Foo<T extends Bar> {
    Bar[] array = new Bar[200];

    Optional<T> forIndex(int index) {
        return Optional.ofNullable(array[index]);
    }
}

      

T

extension required Bar

What does it mean T

should never have a casting problem, or am I accepting that? Can someone clarify.

+3


source to share


1 answer


This is not the case with you. Everyone T

is Bar

, but not everyone Bar

is T

. T

more specialized than Bar

(every daughter is a dog, but not every dog ​​is a dacha). This means it is return Optional.ofNullable(array[index]);

trying to match a Bar

to a T

, which is not possible.

What you can do is just the generic method:



public class Main {
    Bar[] array = new Bar[200];

    Optional<? super Bar> forIndex(int index) {
        return Optional.ofNullable(array[index]);
    }
}

      

You might want to look at this wiki page and googling PECS

might help too.

+5


source







All Articles