A Java class cannot have two overloaded methods that will have the same signature after type erasure. Java will generate a compile-time error for the below scenario:
public class Example {
public void print(Set<String> strSet) { }
public void print(Set<Integer> intSet) { }
}
But my question is not that. There are two scenarios 1 and 2. I want to know, why their behavior is not the same?
Scenario 1:
import java.util.ArrayList;
import java.util.List;
public class MethodOverload {
public static void main(String[] args) {
MethodOverload methodOverload = new MethodOverload();
//Point 1 - List here
List<Integer> mangoList = new ArrayList<Integer>();
mangoList.add(1);
mangoList.add(2);
System.out.println("Size List<Integer>:"+methodOverload.count(mangoList));
//Point 2 - ArrayList here
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("Anex");
nameList.add("Alia");
nameList.add("Maxim");
System.out.println("Size List<String>:"+methodOverload.count(nameList));
}
public <T> int count(List<T> list) {
System.out.print("Ïn side generic; ");
return list.size();
}
}
Output, for Scenario 1:
Inside generic block; Size List<Integer> : 2
Inside generic block; Size List<String> : 3
Scenario 2:
import java.util.ArrayList;
import java.util.List;
public class MethodOverload {
public static void main(String[] args) {
MethodOverload methodOverload = new MethodOverload();
//Point 3 - List here
List<Integer> mangoList = new ArrayList<Integer>();
mangoList.add(1);
mangoList.add(2);
System.out.println("Size List<Integer>:"+methodOverload.count(mangoList));
//Point 4 - ArrayList here
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("Anex");
nameList.add("Alia");
nameList.add("Maxim");
System.out.println("Size List<String>:"+methodOverload.count(nameList));
}
public <T> int count(List<T> list) {
System.out.print("Inside generic block; ");
return list.size();
}
//Point 5
public int count(ArrayList<String> list) {
System.out.print("Inside non-generic block; ");
return list.size();
}
}
Output, for scenario 2:
Inside generic block; Size List<Integer> : 2
Inside non-generic block; Size List<String> : 3
Now, my question is, how does java decide which method will call in the case of scenario 2?
In scenario 1, where java called a single count method without any issue, then why does not java show similar behavior for scenario 2?