2 回答

TA貢獻(xiàn)1810條經(jīng)驗 獲得超5個贊
如果我正確理解您的要求,您想打印出兩個對象中不相同的屬性值,那么您可以創(chuàng)建如下方法。
public void compareAttributes(COSTOS other) {
if (this.getMonto() != other.getMonto()) {
System.out.println("Not equal. This obj : " + this.getMonto()
+ " Other obj : " + other.getMonto());
}
// you can do the same for the remaining attributes.
}
編輯:
正如@Andreas 在評論中指出的,您應(yīng)該將此方法放在您的COSTOS類本身中,以便可以輕松比較每個對象。

TA貢獻(xiàn)1796條經(jīng)驗 獲得超7個贊
首先,可以使用ObjectsJava 7 中添加的空安全輔助方法來簡化您的方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(this.NumeroParte);
result = prime * result + Objects.hashCode(this.descripcion);
result = prime * result + Double.hashCode(this.monto);
result = prime * result + this.referencia;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
COSTOS other = (COSTOS) obj;
return (Objects.equals(this.NumeroParte, other.NumeroParte)
&& Objects.equals(this.descripcion, other.descripcion)
&& Double.doubleToLongBits(this.monto) == Double.doubleToLongBits(other.monto)
&& this.referencia == other.referencia);
}
我如何實現(xiàn)一種可以打印所有不等于的屬性的方法?
要打印差異,請執(zhí)行與equals方法相同的比較:
public void printDifferences(COSTOS other) {
if (! Objects.equals(this.NumeroParte, other.NumeroParte))
System.out.println("Different NumeroParte: " + this.NumeroParte + " != " + other.NumeroParte);
if (! Objects.equals(this.descripcion, other.descripcion))
System.out.println("Different descripcion: " + this.descripcion + " != " + other.descripcion);
if (Double.doubleToLongBits(this.monto) != Double.doubleToLongBits(other.monto))
System.out.println("Different monto: " + this.monto + " != " + other.monto);
if (this.referencia != other.referencia)
System.out.println("Different referencia: " + this.referencia + " != " + other.referencia);
}
添加回答
舉報