Java overload for ArrayList data types

Why can't I use both of these methods in the same class?

public double foo(ArrayList<Integer> x); public double foo(ArrayList<Double> d); 
+4
source share
3 answers

When Java implemented generics to make bytecode backward compatible, they came up with type erasure. This means that at run time there is no general information. So the signatures are valid:

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

and you have two methods with the same signature.

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

Here's the Java Generics Tutorial to Erase Styles .

+4
source

Your problem is that both methods have the same method signature. To overload methods, they must have the same name and return type, but a different method signature, in which case both methods accept a list of arrays.

+1
source

Why aren't you trying to change it to:

 public double fooInteger(ArrayList<Integer> x); public double fooDouble(ArrayList<Double> d); 

I had a similar problem with my applet until I changed the name of the second array.

-2
source

Source: https://habr.com/ru/post/1485690/


All Articles