both method can take the first parameters you've entered f(1,2);
and that's why you get ambiguity.
if you'll do
f((float)1,2);
you won't get the error for example
質問
in java, i'm facing a function ambiguity. basically i'm overloading a variadic function
i'm defining function like
static void f(Integer... a)
{
// .. some statements
}
static void f(float f,Integer... a)
{
// .. some other statements
}
can calling the function with following function calls
f(1,2);
f(1.2f,1,2);
and this error message pops up
error: reference to f is ambiguous, both method f(Integer...) in Test and method f(float,Integer...) in Test match
f(1,2);
^
can someone help me to understand if i'm missing any basic concept in java here. thnx ..
解決
both method can take the first parameters you've entered f(1,2);
and that's why you get ambiguity.
if you'll do
f((float)1,2);
you won't get the error for example
他のヒント
In Java language, int values can be automatically casted to float values (The opposite is not allowed).
Therefore, when you make a call to
f(1,2)
Java compiler matches all possible signatures that automatic type-conversions allow, i.e:
There resides the ambiguity for which the compiler does not know if you meant to call f(int, ...) or f(float, float).
When several methods are applicable, the compiler tries to find the most specific one. If two methods are maximally specific, there is an ambiguity and you get an error.
In summary (the actual rules are a little more complicated):
f(1, 2)
, both methods are applicable (1 can be an integer or a float)float
and Integer
(examples: if you had a f(int i, Integer... j)
vs. f(float f, Integer... j)
, the former would be more specific because int
is more specific than float
among primitives. Similarly, if you had a f(Number f, Integer... i)
vs. a f(Integer... i)
, the latter would be more specific because Integer
extends Number
).The runtime can choose to cast the function with the list of integers to call either function. That's where the confusion lies. Any list of integers you supply can also be turned into another call with the single leading float followed by a list of integers.