In Java type arguments, does <? extends E> mean strictly subtypes only? or would E also suffice?
Asked Answered
R

3

8

In Java type arguments, does mean strictly subtypes only? or would E also suffice?

Riding answered 28/6, 2010 at 22:43 Comment(0)
T
6

Yes, super and extends gives inclusive lower and upper bounds respectively.

Here's a quote from Angelika Langer's Generics FAQ:

What is a bounded wildcard?

A wildcard with an upper bound looks like ? extends Type and stands for the family of all types that are subtypes of Type , type Type being included. Type is called the upper bound.

A wildcard with a lower bound looks like ? super Type and stands for the family of all types that are supertypes of Type , type Type being included. Type is called the lower bound.

Top answered 29/6, 2010 at 7:51 Comment(2)
This doesn't reflect my observations. If I write method that accepts <T extends E>, I get error if I try to pass E instance.Gerbold
@TomášZato: The answer is correct; example: ideone.com/hRZFlu. Suggest removing the comment (and flagging this one as obsolete). If there's a specific example you have where it doesn't seem to work, you might want to post a question about that, it's probably something similar but different. :-)Langobard
W
7

It's not strict; E would suffice.

Workman answered 28/6, 2010 at 22:47 Comment(2)
I presume the converse is true as well? i.e. <? super E> is not strict and can mean E as well. Thanks!Riding
Yes, E satisfies <? super E> as well.Workman
T
6

Yes, super and extends gives inclusive lower and upper bounds respectively.

Here's a quote from Angelika Langer's Generics FAQ:

What is a bounded wildcard?

A wildcard with an upper bound looks like ? extends Type and stands for the family of all types that are subtypes of Type , type Type being included. Type is called the upper bound.

A wildcard with a lower bound looks like ? super Type and stands for the family of all types that are supertypes of Type , type Type being included. Type is called the lower bound.

Top answered 29/6, 2010 at 7:51 Comment(2)
This doesn't reflect my observations. If I write method that accepts <T extends E>, I get error if I try to pass E instance.Gerbold
@TomášZato: The answer is correct; example: ideone.com/hRZFlu. Suggest removing the comment (and flagging this one as obsolete). If there's a specific example you have where it doesn't seem to work, you might want to post a question about that, it's probably something similar but different. :-)Langobard
L
1
List<? extends Animal> animalList=new List<Dog>();
List<? extends Animal> animalList=new List<Animal>();

Both the lines compile without any error. Any function taking the list as a parameter understands that the objects in the list are of type E or a subtype of E.

Larkins answered 29/6, 2010 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.