java比较对象_java怎么比较两个对象是否相等?

女爷i 2022-11-02 00:59 351阅读 0赞

展开全部

首先先确定到底是要判断62616964757a686964616fe59b9ee7ad9431333363373764是同一个对象还是两个对象里面的内容一毛一样,若是要判断是否是同一个对象直接用“==”就好了,若是判断内容是否一毛一样package com.havefun.play;

public class ObjectJudge {

private String name;

private Integer age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

public ObjectJudge(String name, Integer age) {

super();

this.name = name;

this.age = age;

}

// 重写hashcode

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((age == null) ? 0 : age.hashCode());

result = prime * result + ((name == null) ? 0 : name.hashCode());

return result;

}

// 重写equals

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

ObjectJudge other = (ObjectJudge) obj;

if (age == null) {

if (other.age != null)

return false;

} else if (!age.equals(other.age))

return false;

if (name == null) {

if (other.name != null)

return false;

} else if (!name.equals(other.name))

return false;

return true;

}

@Override

public String toString() {

return “Person [name=” + name + “, age=” + age + “]“;

}

public static void main(String[] args) {

ObjectJudge person = new ObjectJudge(“aaa”, 11);

ObjectJudge person2 = new ObjectJudge(“aaa”, 11);

System.out.println(person == person2);

System.out.println(person.equals(person2));

}

}

发表评论

表情:
评论列表 (有 0 条评论,351人围观)

还没有评论,来说两句吧...

相关阅读

    相关 js比较对象是否相等

    > 前言:如何判断两个对象是否相等? 两个Object类型对象,即使拥有相同属性、相同值,当使用 == 或 === 进行比较时,也不认为他们相等。这就是因为他们是通过引用(内