重写equals方法
不重写equals方法就是调用Object的equals方法,比较的是当前对象的地址;如下例:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
}
测试类Test.java
public class Test {
public static void main(String[] args) {
Person p1 = new Person("aaa",10);
Person p2 = new Person("aaa",10);
System.out.println(p1.equals(p2)); //false
}
}
重写equals后的Person类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
@Override
public boolean equals(Object o) {
Person p = (Person) o;
if (this.name.equals(p.name) && this.age == p.age){
return true;
}
return false;
}
}
测试类Test.java
public class Test {
public static void main(String[] args) {
Person p1 = new Person("aaa",10);
Person p2 = new Person("aaa",10);
// System.out.println(p1.equals(p2)); //false
System.out.println(p1.equals(p2)); //true
}
}
由上可以看出,我们需要比较两个对象是不是同一个时,我们一般需要重写equals方法,可以自定义你想要的比较的内容,如上例,你可以认为姓名和年龄相同就认为这是一个对象,此时你只需要在equals里写比较姓名年龄的逻辑就行了,并返回比较的结果;
toString方法
对于tostring方法,如果你没有重写的话,那么同样是默认调用Object的tostring方法,此时打印的是一个地址;
如下是一个Person类;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
@Override
public boolean equals(Object o) {
Person p = (Person) o;
if (this.name.equals(p.name) && this.age == p.age){
return true;
}
return false;
}
}
Test类用于调用tostring方法;
public class Test {
public static void main(String[] args) {
Person p1 = new Person("aaa",10);
Person p2 = new Person("aaa",10);
// System.out.println(p1.equals(p2)); //false
System.out.println(p1.equals(p2)); //true
System.out.println(p1.toString()); //day0715.test02.Person@14ae5a5
}
}
如果你想看到的是一个对象的属性的相关信息此时你就需要重写这个方法;如下:
修改后的Person类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
@Override
public boolean equals(Object o) {
Person p = (Person) o;
if (this.name.equals(p.name) && this.age == p.age){
return true;
}
return false;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Test类;
public class Test {
public static void main(String[] args) {
Person p1 = new Person("aaa",10);
Person p2 = new Person("aaa",10);
// System.out.println(p1.equals(p2)); //false
System.out.println(p1.equals(p2)); //true
// System.out.println(p1.toString()); //day0715.test02.Person@14ae5a5
System.out.println(p1.toString()); //Person{name='aaa', age=10}
}
}