C graphics
C graphics

Reputation: 7458

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);

Upvotes: 5

Views: 4968

Answers (3)

user2465406
user2465406

Reputation: 189

Why don't you try 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.

Upvotes: -2

Mario Dennis
Mario Dennis

Reputation: 3016

Your problem is that both methods have the same method signature. To overload methods they must have the same name and return type but different method signature, in you case both method accepts a array list.

Upvotes: 1

rgettman
rgettman

Reputation: 178303

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.

Upvotes: 4

Related Questions