0

I know the difference between a Collection<?>, Collection<Object> and Collection.

The first takes any type only, the second must allow all Objects, and the third is unchecked.

But for a single instance (non Collection), e.g. ScheduledFuture<?>, ScheduledFuture<Object> and ScheduledFuture, what is the difference? It seems that they all allow everything.

discipliuned
  • 916
  • 7
  • 13

2 Answers2

2

The Java Language Specification writes:

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of generics into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

That leaves the other two. As ScheduledFuture only uses its type parameter in a method return type, ScheduledFuture<?> (which is the same as ScheduledFuture<? extends Object>) is equivalent to ScheduledFuture<Object> to calling code.

However, code that actually creates an instance of a ScheduledFuture needs to work with a subclass of ScheduledFuture, and may care a great deal about the type parameter that subclass implements ScheduledFuture with.

When declaring a method that returns a ScheduledFuture, you will therefore want to use the type ScheduledFuture<?> as that signature is easier to implement for the producer of the ScheduledFuture, but equally useful to its consumer. (This is simply a special case of the PECS rule.)

Community
  • 1
  • 1
meriton
  • 68,356
  • 14
  • 108
  • 175
0

They are not interchangeable. Collection without a type specifier is unbound, and thus its API methods will return Object by default. See this question for a good explanation of the difference between Collection<?> and Collection<Object>: What is the difference between ? and Object in Java generics?.

Community
  • 1
  • 1
cogitos
  • 336
  • 1
  • 4
  • I'm not looking for whether the 3 Collections are interchangeable, I know they are not. I am interested in the 3 ScheduledFutures mentioned – discipliuned Sep 30 '14 at 20:22