代码一:
import java.util.ArrayList;
import java.util.List;
public class Test004 {
public static void main(String[] args) {
List lst = new ArrayList<String>();
lst.add(1);
lst.add("Test004");
List<Integer> ls = lst;
ls.add(2);
for (int i = 0; i < ls.size(); i++) {
System.out.println(ls.get(i));
}
}
}
代码二:
import java.util.ArrayList;
import java.util.List;
public class Test005 {
public static void main(String[] args) {
List lst = new ArrayList<String>();
lst.add(1);
lst.add("Test004");
List<String> ls = lst;
ls.add("Test0041");
for (int i = 0; i < ls.size(); i++) {
System.out.println(ls.get(i));
}
}
}
PrintStream类中有println(Object x), println(String x),但是没有println(Integer x)
List<Integer> ls = lst;
执行的是println(Object x),先执行String.valueOf(x), 然后再用print(String)打印,所以不会出错。
List<String> ls = lst;
执行的是println(String x)方法,Integer转String出错。
- public void println(String x) {
- synchronized (this) {
- print(x);
- newLine();
- }
- }
- /**
- * Prints an Object and then terminate the line. This method calls
- * at first String.valueOf(x) to get the printed object's string value,
- * then behaves as
- * though it invokes <code>{@link #print(String)}</code> and then
- * <code>{@link #println()}</code>.
- *
- * @param x The <code>Object</code> to be printed.
- */
- public void println(Object x) {
- String s = String.valueOf(x);
- synchronized (this) {
- print(s);
- newLine();
- }
- }