I know about overloading rules in Java, but for some situations my intuition doesn't work.
Let's consider an example:
public class Overloading {
public static void main(String[] args) {
long primitive = 3;
Long boxed = Long.valueOf(5);
doWork(primitive, boxed); //1
doWork(boxed, boxed); //2
doWork(primitive, primitive); //3
}
static void doWork(Long a, Long b) {}
static void doWork(long a, Long b) {}
}
Do you know what (1, 2 or 3) will be compiled successfully?
The first and the second will, but third won't (due to ambitious method call).
Why is javac designed this way and can't resolve this situation? Why not to cast #3 to #1?
Good Question!
You're suggestion that #3 should be cast to #1 does seem to make sense, because it has one less auto-boxing to do.
This is probably the reasoning behind Java's decision to give you an error instead of picking the method with the least boxing involved:
*The accepted answer to the question linked to by Sotirios gives some insight into why it might by too expensive to be worth it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With