Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java overloading for ArrayList data types

Why I can not have both of this two methods in same class?

public double foo(ArrayList<Integer>  x);
public double foo(ArrayList<Double>  d);
like image 934
C graphics Avatar asked Oct 21 '22 07:10

C graphics


1 Answers

When Java implemented generics, to make the bytecode backwards compatible, they came up with type erasure. That means that at runtime, the generic information is gone. So the signatures are really:

public double foo(ArrayList  x);
public double foo(ArrayList  d);

and you have two methods with the same signature.

The solution here would be not to overload the method name; name the two methods different names.

Here's the Java Generics Tutorial Page on type erasure.

like image 163
rgettman Avatar answered Oct 24 '22 16:10

rgettman