generics Object.getClass clarification. "<?>" vs "<? extends Object>"

O

odwl

Hi,

First, it seems to me that <T> is completely redundant with <T extends
Object>.
Indeed I can cast without warning List<T> and List<T extends Object> in
both way
Could someone confirm? Is that specifically said in the spec? Is that
really really equivalent?

Second, for the same reason, I also think that <?> is equivalent to <?
extends Object>.
Could someone confirm?

Third, the signature of the method Object.getClass() is:
Class<? extends Object> getClass().
Why they didn't write the following simple simple instead:
Class<?> getClass().

I know that there is a "trick" here in the sense that that methods does
not really return <? extends Object> but <? extends X> where X is the
erasure of the static type (as mentioned in the javadoc) so perhaps
they just choose <? extends X> because it is more "similar"!!

Could have they choose Class<?>. in place of Class<? extends Object>?
Was the choice made by chance?

Regards,


Olivier
 
T

Thomas Hawtin

odwl said:
First, it seems to me that <T> is completely redundant with <T extends
Object>.

The extends Object is redundant, I think.
Indeed I can cast without warning List<T> and List<T extends Object> in
both way
Could someone confirm? Is that specifically said in the spec? Is that
really really equivalent?

You can't cast to a generic type without warnings. And I don't think
extends/super makes sense in a cast, but you are using rather than
declaring the generic parameter.
Second, for the same reason, I also think that <?> is equivalent to <?
extends Object>.
Could someone confirm?
Yup.

Third, the signature of the method Object.getClass() is:
Class<? extends Object> getClass().
Why they didn't write the following simple simple instead:
Class<?> getClass().

It is in 1.6. It's fudged by the compiler/language spec. If you call
getClass on List<String> you get a result of type Class<? extends List>.
The 1.6 docs have more details (and there is a bug in the Bug Parade
covering the change).

"public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object
is the object that is locked by static synchronized methods of the
represented class.

The actual result type is Class<? extends |X|> where |X| is the
erasure of the static type of the expression on which getClass is
called. For example, no cast is required in this code fragment:

Number n = 0;
Class<? extends Number> c = n.getClass();"

http://download.java.net/jdk6/docs/api/java/lang/Object.html#getClass()

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top