在Java中需要比较两个对象时,通常需要重写equals方法和hashcode方法。
package com.gds.ai;
public class Student {
private String address;
private String name;
private int age;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {}
public Student (String address, String name, int age) {
this.address = address;
this.age = age;
this.name = name;
}
public boolean equals(Object o) {
if (o == this) {return true;}
if (!(o instanceof Student)) {
return false;
}
Student std = (Student) o;
return std.address.equals(address) &&
std.name.equals(name)&& std.age == age;
}
public int hashcode() {
int result = 17;
result = 31*result + address.hashCode();
result = 31*age + age;
result = 31*result + name.hashCode();
return result;
}
public static void main(String[] args) {
Student stu1 = new Student("中国","张三",15);
Student stu2 =new Student("中国","张三",18);
System.out.println(stu1.equals(stu2));
}
}