通过编译器自己生成equals方法来判断两个对象是否一样
package demo2;
import java.util.Objects;
class Student {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
/**/
public class test {
public static void main(String[] args) {
Student student1=new Student("张三",18);
System.out.println(student1);
//每次new都会在堆上出现一个新的
Student student2=new Student("张三",18);
//比较的是地址
System.out.println(student1==student2);
System.out.println(student1.equals(student2));
//谁调用了equals就是this
//public boolean equals(Object obj);
//return (this==equals);
//equal的内函数
}
}
调用student1.equals(student2)判断赋值是否相同
如果是以后自定义方法类型一定要记住重写equals方法