Java 比较两个对象属性值并获取差异属性集合
假设我们有一个 Person 类,有 name、age、gender 等属性,以下是比较两个 Person 对象各属性值是否相同并返回属性值不同的属性集合的示例代码:
import java.util.HashSet;
import java.util.Set;
public class Person {
private String name;
private int age;
private String gender;
// 构造方法、Getter和Setter省略
/**
* 比较两个 Person 对象各属性值是否相同
* @param other 另一个 Person 对象
* @return true如果属性值相同,false如果属性值不同
*/
public boolean compare(Person other) {
if (other == null) {
return false;
}
if (!this.name.equals(other.getName())) {
return false;
}
if (this.age != other.getAge()) {
return false;
}
if (!this.gender.equals(other.getGender())) {
return false;
}
return true;
}
/**
* 返回属性值不同的属性集合
* @param other 另一个 Person 对象
* @return 属性值不同的属性集合
*/
public Set<String> getDifferentProperties(Person other) {
Set<String> differentProperties = new HashSet<>();
if (!this.name.equals(other.getName())) {
differentProperties.add('name');
}
if (this.age != other.getAge()) {
differentProperties.add('age');
}
if (!this.gender.equals(other.getGender())) {
differentProperties.add('gender');
}
return differentProperties;
}
}
使用示例:
Person p1 = new Person('Tom', 20, 'male');
Person p2 = new Person('Tom', 21, 'male');
boolean same = p1.compare(p2); // false
Set<String> differentProperties = p1.getDifferentProperties(p2); // {'age'}
原文地址: https://www.cveoy.top/t/topic/n8ab 著作权归作者所有。请勿转载和采集!