我有一个包含旧数据和新数据变量的类。
例子:
class Person{
String newAddress;
int newMobileNumber;
String newOfficeId;
// many fields like this (atleast 15 fields)
String oldAddress;
int oldMobileNumber;
String oldOfficeId;
// many fields like this (atleast 15 fields)
//getters and setters of all the fields.
}
我正在做的是点击按钮将旧数据和新数据存储在一个表中,该表由与字段同名的列组成(用于跟踪旧数据)
但是如果所有的 oldFields 都等于 newFields 我想避免避免数据库操作。
一种方法是使用多个 if 条件。像这样,
if(oldAddress.equals(newAddress)){
flag = true;
}
if(oldMobileNumber.equals(newMobileNumber)){
flag = true;
}
所以我需要很多这样的 if()
,我觉得这个解决方案不太好。我怎样才能更好地做到这一点?
最佳答案
您也可以在 Person
类中丢弃所有这些 double 值,而只创建一个 Person 变量来存储旧值。您可以只更新 setter 方法中的旧值。要检查是否有任何值发生更改,您可以覆盖 equals 方法并将当前对象与 Person 类中的 olvValues
变量进行比较。
由于这种方式,如果您在某个时候向您的 Person 类添加变量,您可以确保自己做一些额外的工作。
这可能看起来像这样。
public class Person{
String address;
int mobileNumber;
String officeId;
// many fields like this (atleast 15 fields)
private Person oldValues;
public Person(String address, int mobileNumber, String officeId) {
this.address = address;
this.mobileNumber = mobileNumber;
this.officeId = officeId;
oldValues = new Person(this);
}
public Person(Person p) {
this.address = p.address;
this.mobileNumber = p.mobileNumber;
this.officeId = p.officeId;
}
// Your method that checks if any value did change.
public void checkIfValuesChanged() {
if(this.equals(oldValues)) {
// Nothing changed
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + mobileNumber;
result = prime * result + ((officeId == null) ? 0 : officeId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if(!(obj instanceof Person)) return false;
Person other = (Person) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (mobileNumber != other.mobileNumber)
return false;
if (officeId == null) {
if (other.officeId != null)
return false;
} else if (!officeId.equals(other.officeId))
return false;
return true;
}
// Your setter methods do save the old values in the oldValues Person object
public void setAddress(String address) {
oldValues.address = this.address;
this.address = address;
}
}
关于java - 比较同一类变量的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33151922/