import java.util.*;class Student { private String name; private String phone; public Student(String name, String phone) { this.name = name; this.phone = phone;
} public String toString() {
return name + ":" + phone;
}
}public class Test4 { public static void main(String[] args) { Student st1 = new Student("John", "23214"); Student st2 = new Student("Alice", "4563"); List<Student> list = new ArrayList<Student>(); list.add(st1);
list.add(st2); for (int i = 0; i < list.size(); i++) System.out.println(list.get(i)); }}
} public String toString() {
return name + ":" + phone;
}
}public class Test4 { public static void main(String[] args) { Student st1 = new Student("John", "23214"); Student st2 = new Student("Alice", "4563"); List<Student> list = new ArrayList<Student>(); list.add(st1);
list.add(st2); for (int i = 0; i < list.size(); i++) System.out.println(list.get(i)); }}
/**
* 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();
}
}
在看下 String.valueOf的源码
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}是不是觉得自己明白了?通俗的说,就是,调用System.out.println 这个方法的时候,如果传入参数为对象(Object)的时候,
就会调用这个对象的ToString方法~~每一个类都是继承于Object而Object中有一个这样的方法
/**
* Returns a string representation of the object. In general, the
* <code>toString</code> method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The <code>toString</code> method for class <code>Object</code>
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `<code>@</code>', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
继承Object的类如果不重写toString方法,就会调用Object里面的方法也就是说,如果你的Student类不重写toString打印出来的应该是类名+哈希值
不明白执行流程就断点、debug