Strange behavior when overloading methods in Java
Posted
by Sep
on Stack Overflow
See other posts from Stack Overflow
or by Sep
Published on 2010-05-31T21:49:38Z
Indexed on
2010/05/31
21:53 UTC
Read the original article
Hit count: 168
java
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.
© Stack Overflow or respective owner