重写toString()、equals()、hashcode()、compareTo()、compare()
接下来将从两方面分析
- 为什么要重写这几个方法?
- 怎么重写这几个方法?
toString()
public class Student {
String name;
int age;
String address;
public Student() {
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
}
}
public class testForStudent {
public static void main(String[] args) {
Student st1 = new Student("嘉文四世",20,"德玛西亚");
Student st2 = new Student("卡萨丁",50,"虚空");
Student st3 = new Student("卡莎",18,"虚空");
Student st4 = new Student("提莫",6,"扭曲丛林");
Student st5 = new Student("寒冰",18,"弗雷尔卓德");
Student st6 = new Student("寒冰",18,"弗雷尔卓德");
System.out.println(st1);
}
}
输出是:
indiv.zcg.day912.Student@1b6d3586
如果不重新toString()方法,toString方法默认输出的是对象的地址!像String、Interger这种类其实都已经将toString重写了
查阅代码可知
public String toString() {
return this;
}
如果不重写toString,即Object类中的
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
这就解释了为什么上面我们的输出是一个类全限类名@一个16进制数
那么如何重写?
public class Student {
String name;
int age;
String address;
public Student() {
}
public