这两天看一些简单的代码以从新拾起java,发现了一点不太明白的地方,也就是System.out.println(Object obj)的输出问题,通过看源代码也算是弄明白了,挺简单,只是平时没怎么注意到。仅供java初学者参考。
先来看下这段代码:
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
System.out.println(set);
Set<Student> studs=new TreeSet<Student>();
studs.add(new Student(1,"tom","123"));
studs.add(new Student(2,"jerry","123"));
studs.add(new Student(3,"kitty","123"));
studs.add(new Student(4,"superman","123"));
System.out.println(studs);
}
}
控制台的输出是这样的:
[id:1,name:tom;pass:123, id:2,name:lilei;pass:234, id:3,name:hanmeimei;pass:345, id:4,name:kate;pass:456]
一开始没太在意,以为这输出格式是默认的,后来想到我只是在给输出方法一个引用参数,它是怎么识别并且这样输出里面的内容的?
Student类如下:
public class Student implements Comparable {
private int id;
private String name;
private String pass;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(int id, String name, String pass) {
super();
this.id = id;
this.name = name;
this.pass = pass;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public String toString() {
return "id:"+id+",name:"+name+";pass:"+pass;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + id;
result = PRIME * result + ((name == null) ? 0 : name.hashCode());
result = PRIME * result + ((pass == null) ? 0 : pass.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Student other = (Student) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (pass == null) {
if (other.pass != null)
return false;
} else if (!pass.equals(other.pass))
return false;
return true;
}
public int compareTo(Object o) {
if(o instanceof Student){
Student stu=(Student)o;
return this.id-stu.id;
}
else{
return this.hashCode()-o.hashCode();
}
}
}
注意到,这里面重载了toString方法,其设置的输出格式和上面我们有疑问的地方很像。我们再来看println方法的源代码:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
这里面用了print输出了一个字符串,而这个字符串引用了String.valueOf(x),查看API,String类的valueOf静态方法:
public static String valueOf(Object obj)返回 Object 参数的字符串表示形式。
参数:obj - 一个 Object。
返回:如果参数为 null,则字符串等于 "null";否则,返回 obj.toString() 的值。
看见了吧,返回时调用了toString方法,因此有疑问的输出格式问题也就解决了。