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?
extends Number> represents a list of Number or its sub-types such as Integer and Double. Lower Bounded Wildcards: List<? super Integer> represents a list of Integer or its super-types Number and Object.
There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
formal parameter — the identifier used in a method to stand for the value that is passed into the method by a caller. actual parameter — the actual value that is passed into the method by a caller. For example, the 200 used when processDeposit is called is an actual parameter.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With