Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between generic method and non-generic method

Tags:

java

generics

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);
like image 773
Ori Popowski Avatar asked Mar 12 '26 05:03

Ori Popowski


2 Answers

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.

like image 95
JB Nizet Avatar answered Mar 16 '26 06:03

JB Nizet


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.

like image 25
aliteralmind Avatar answered Mar 16 '26 04:03

aliteralmind