Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method overload - ambiguity

While I was doing some runs to test some code in this thread I found out a strange thing, If you consider the following program

import java.util.ArrayList;
import java.util.List;

public class OverloadTest {

    public String test1(List l){
        return "abc";
    }

    public int test1(List<Integer> l){
        return 1;
    }

    public static void main(String [] args) {
        List l = new ArrayList();
        System.out.println(new OverloadTest().test1(l));
    }
}

I was expecting Java compiler to show ambiguity error due to byte-code Erasure property, but it didn't. Now when I tried to run this code, I was expecting that test1(List) will be called and the output would be "abc" but to my surprise it called test1(List<Integer>) (output was 1)

I even tried like below

List l = new ArrayList();
l.add("a");
System.out.println(new OverloadTest().test1(l));

But still found Java calling test1(List<Integer> param) method and when i inspected the param it had the String "a" ( how did Java cast List<String> to List<Integer> ?)

like image 566
sanbhat Avatar asked May 04 '13 19:05

sanbhat


People also ask

How do you overcome ambiguity in Java?

The inclusion of generics gives rise to a new type of error that you must guard against ambiguity. Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading.

What is ambiguous method call in Java?

This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.

What is method overloading in Java with example?

In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... } void func(int a) { ... }

How can overloading method be resolved?

The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done). As expected the output is 10.


1 Answers

This is a fixed bug. https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229

It looks like this bug existed in javac5, javac6 and ecj for Eclipse 3.7, but it was fixed in Eclipse 3.8 and later.

like image 71
durron597 Avatar answered Oct 15 '22 23:10

durron597