This is from Effective java Item 26.
I'm not clear why the method does not call method1,2 in the for loop.
it says in method overloading the method is selected when compile time not run time.
help me out what is "the method is selected when compile time not run time."
thanks in advance.
import java.util.*;
public class Test {
public static String classify(Set s) { // method1
return "Set";
}
public static String classify(List l) { // method2
return "List";
}
public static String classify(Collection c) { //method3
if(c instanceof Set){
System.out.println("instanceof Set");
}
if(c instanceof List){
System.out.println("instanceof List");
}
return "Unknown Collection";
}
public static void main(String[] args) {
Collection[] tests = new Collection[] { new HashSet(), // A Set
new ArrayList(), // A List
new HashMap().values() // Neither Set nor List
};
for (int i = 0; i < tests.length; i++){
System.out.println(classify(tests));
}
System.out.println(classify(new HashSet()));
System.out.println(classify(new ArrayList()));
System.out.println(classify(new HashMap().values()));
}
}
I'm not clear why the method does not call method1,2 in the for loop.
it says in method overloading the method is selected when compile time not run time.
help me out what is "the method is selected when compile time not run time."
thanks in advance.
import java.util.*;
public class Test {
public static String classify(Set s) { // method1
return "Set";
}
public static String classify(List l) { // method2
return "List";
}
public static String classify(Collection c) { //method3
if(c instanceof Set){
System.out.println("instanceof Set");
}
if(c instanceof List){
System.out.println("instanceof List");
}
return "Unknown Collection";
}
public static void main(String[] args) {
Collection[] tests = new Collection[] { new HashSet(), // A Set
new ArrayList(), // A List
new HashMap().values() // Neither Set nor List
};
for (int i = 0; i < tests.length; i++){
System.out.println(classify(tests));
}
System.out.println(classify(new HashSet()));
System.out.println(classify(new ArrayList()));
System.out.println(classify(new HashMap().values()));
}
}