-1

I'm trying to learn generics and I had some questions about wildcards and their use.

What is the difference between the wildcards for upper and lower bounds and specifically what is the difference between: <? extends Object> and <? extends T> in java?

James Drinkard
  • 15,342
  • 16
  • 114
  • 137
Don Miller
  • 141
  • 1
  • 9

2 Answers2

1

Check here for your question on "upper and lower bounds" - SO link.

For an overview on generics check here

As for the difference between <? extends Object> and <? extends T>, the former is a type that is bound by the type java.lang.Object whereas the latter is bound by the type variable T - meaning you can satisfy by any type that extends java.lang.Object(which is all Java types) in the former and in the latter, you can satisfy by any type that extends the type T. Remember that T can be anything - even java.lang.Object.

Community
  • 1
  • 1
Seeta Somagani
  • 776
  • 1
  • 11
  • 31
0

<? extends Object> is ALMOST useless. All that means is you're working with something that is not a primitive type. <? extends T> means you're working with an object that is of type T or a subclass of T and has whatever methods and fields T has.

<? extends T> is useful to declare what an Object is expected to contain. It limits the scope of the container or the method which adds funcionality to the method/container.

For Example:

public class foobination<T extends foo>
{
   private <? extends T> foo;

   public foobination(T foo)
   {
      this.foo = foo;
   }

   public getFoo() { return foo; }

   public void myFoobinator(<? extends T> foob)
   {
     foo.bash("foobinator was here");
     foo.setBang(foob.getBang());
   }
}

the other common use case would be: List<? extends T> Where you're storing a collection of something and you don't know exactly what it is but you do know they will all be a subclass of whatever T is. That way you at least have some idea of what to expect to get back out of the collection.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Raystorm
  • 6,180
  • 4
  • 35
  • 62