Strange behavior when overloading methods in Java
- by Sep
I came across this weird (in my opinion) behavior today. Take this simple Test class:
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.run();
}
private void run() {
List<Object> list = new ArrayList<Object>();
list.add(new Object());
list.add(new Object());
method(list);
}
public void method(Object o) {
System.out.println("Object");
}
public void method(List<Object> o) {
System.out.println("List of Objects");
}
}
It behaves the way you expect, printing "List of Objects". But if you change the following three lines:
List<String> list = new ArrayList<String>();
list.add("");
list.add("");
you will get "Object" instead.
I tried this a few other ways and got the same result. Is this a bug or is it a normal behavior? And if it is normal, can someone explain why?
Thanks.