Reputation: 10662
What is the difference between these two methods?
public <T extends Serializable, Y extends List<T>> void foo(Y y, T t);
and
public void foo(Serializable ser, List<Serializable> list);
Upvotes: 3
Views: 3333
Reputation: 20163
public <T extends Serializable, Y extends List<T>> void foo(Y y, T t);
The generics in this function force you specify exactly what type T
is, and it must be exactly the same in both parameters. A sub-class of T
is not allowed, it must be that type. The compiler will not allow otherwise.
public void foo(Serializable ser, List<Serializable> list);
In this non-generic function, there is no relation between the types of the parameters, other than they are both Serializable
. This allows ser
to be any type of Serializable
, and the elements in list
to be any type of Serializable
. They may be the same type, they may not. It doesn't matter to the compiler.
A bit more information for any newbies that might be reading this:
Generics only exist in source code. They do not exist once the code is compiled. This is called "type erasure":
https://www.google.com/search?q=type+erasure+java
This erasure is done so pre-generics code can interoperate with generics code. So code that existed before generics was introduced would not have to be changed. New code is encouraged to always use generics.
Upvotes: 3
Reputation: 691715
The first one can be called with a List<String>
(for example) as argument. The second one can't, because a List<String>
is not a List<Serializable>
.
The second one can be called with an Integer
as first argument, and a List<Serializable>
as second argument. The first one, however, will only accept a List<Integer>
as argument if the other argument is an Integer
.
Upvotes: 5