目录
实验要求
编写一Person类,通过重写toString()、equals()、hashcode()方法,实现可以对Person类实例化出的对象进行equals和==的比较。
实验内容
package test5;
import java.util.Objects;
class person {
String sex;
int age;
String name;
boolean notempty;
public person(String sex,int age,String name){
this.sex = sex;
this.age = age;
this.name = name;
this.notempty = true;
}
@Override
public String toString() {
return "person{" +
"sex='" + sex + '/'' +
", age=" + age +
", name='" + name + '/'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
person person = (person) o;
return age == person.age && sex.equals(person.sex) && name.equals(person.name);
}
@Override
public int hashCode() {
return Objects.hash(sex, age, name);
}
public static void main(String args[]){
person p1 = new person("男",20,"张三");
person p2 = new person("男",20,"张三");
System.out.println("p1 is " + p1 );
System.out.println("p2 is " + p2 );
System.out.println(p1.hashCode() == p2.hashCode());
System.out.println(p1 == p2);
System.out.println(p1.equals(p2));
}
}
原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/244387.html