25

What is the difference with a method declaration like this:

public <T extends SomeClass> void doSomething(T obj)
{
    // Do something.
}

And this:

public void doSomething(SomeClass obj)
{
    // Do Something.
}

The way I see it, both of them are specifying that the object passed in must be a subclass of type SomeClass, so why bother with the generics at all in this instance?

Roman C
  • 49,761
  • 33
  • 66
  • 176
christopher
  • 26,815
  • 5
  • 55
  • 89
  • 4
    I've often wondered this but didn't have enough courage to ask for fear of the dreaded {-1}s. So +1. – Bathsheba Dec 18 '13 at 15:19
  • 3
    To say "java generics are completely useless" is a bold and incorrect statement. I don't deny they're flawed and fully featured, but that doesn't make them useless – Brian Agnew Dec 18 '13 at 15:21
  • 1
    Good god, sorry again, I don't seem to be able to read so I'm going home. In the case above, no point, but in other specific cases it can be useful, as per the answer from micha below. The implementation is for the developer and not the computer, for those cases when it happens to be useful for the person! – RossC Dec 18 '13 at 15:25
  • An example of when you would have to use this; [Returning a Collection from a method that specifies that it returns Collection](http://stackoverflow.com/questions/17384015/returning-a-collectionchildtype-from-a-method-that-specifies-that-it-returns-c) – Richard Tingle Dec 18 '13 at 15:30
  • In the above example I don't see a difference, but if the return type was of type T, it would. In that case, client code wouldn't have to cast. – splungebob Dec 18 '13 at 15:35
  • Very similar: [Type arguments in Java](http://stackoverflow.com/questions/19934304/type-arguments-in-java) – Paul Bellora Dec 18 '13 at 15:47
  • possible duplicate of [What does – Dennis Meng Dec 18 '13 at 15:56

1 Answers1

29

In your case it doesn't make much difference.

But consider the following:

public <T extends SomeClass> void doSomething(List<T> obj)

In this case you could call the method the following ways:

obj.doSomething(new ArrayList<SubclassOfSomeClass>());
obj.doSomething(new ArrayList<SomeClass>());

If you would use

public void doSomething(List<SomeClass> obj)

You would only be able to do this:

obj.doSomething(new ArrayList<SomeClass>());
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
micha
  • 47,774
  • 16
  • 73
  • 80