Question

I have been asked this question in an interview.

can anyone explain it.

public class A{

     public void show(List <String>list1,List<Integer>lists2){...}

     public void show(List <Integer>list1,List<String>lists2){...}
}
public class B{
 public static void main(..){
    A a=new A();
    List<String> list1;
    List<Integer>lists2;
    a.show(list1,lists2);
     }
   }

I said 2 function would be called.. but when i worte in neatbeans it gave error of same name function been called...??? why so isnt overloading concept used here???

Was it helpful?

Solution 2

Java Generics are enforced at compile time, but the type of the Collection is erased, and what you're left with is a duplicate method. In an IDE, you would get some message about "same type erasure."

Here's a good discussion about it that I enjoyed:

http://mindprod.com/jgloss/generics.html

OTHER TIPS

Due to type erasure, the arguments of the method will become List.

public void show(List list1, List list2);
public void show(List list1, List list2);

Thus becoming invalid code.

First, remove "public" from one of your class declaration (actually from class A) .

Second, the compiler is reading the parameter as show(list, list), so it is giving you the same method and there is no overloading occurring here. As both parameters are show(list, list).

Remember, generics are used to distinguish the object type not the return type.

Hope it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top