希望这会对你有所帮助,这是你的课程:
- Class CustomObj 覆盖对象的
equal 方法,在实现中我将CustomObj 类的属性与CustomKey 进行比较
自定义对象:
public class CustomObj {
Long key1;
Integer key2;
Integer key3;
Integer key4;
Integer key5;
BigDecimal value1;
BigDecimal value2;
BigDecimal value3;
BigDecimal value4;
BigDecimal value5;
public CustomObj(Long k1, Integer k2, Integer k3, Integer k4, Integer k5){
this.key1 = k1;
this.key2 = k2;
this.key3 = k3;
this.key4 = k4;
this.key5 = k5;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key1 == null) ? 0 : key1.hashCode());
result = prime * result + ((key2 == null) ? 0 : key2.hashCode());
result = prime * result + ((key3 == null) ? 0 : key3.hashCode());
result = prime * result + ((key4 == null) ? 0 : key4.hashCode());
result = prime * result + ((key5 == null) ? 0 : key5.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
CustomKey other = (CustomKey) obj;
if (key1 == null) {
if (other.key1 != null)
return false;
} else if (!key1.equals(other.key1))
return false;
if (key2 == null) {
if (other.key2 != null)
return false;
} else if (!key2.equals(other.key2))
return false;
if (key3 == null) {
if (other.key3 != null)
return false;
} else if (!key3.equals(other.key3))
return false;
if (key4 == null) {
if (other.key4 != null)
return false;
} else if (!key4.equals(other.key4))
return false;
if (key5 == null) {
if (other.key5 != null)
return false;
} else if (!key5.equals(other.key5))
return false;
return true;
}
}
自定义密钥:
public class CustomKey {
Long key1;
Integer key2;
Integer key3;
Integer key4;
Integer key5;
public CustomKey(Long k1, Integer k2, Integer k3, Integer k4, Integer k5){
this.key1 = k1;
this.key2 = k2;
this.key3 = k3;
this.key4 = k4;
this.key5 = k5;
}
}
To Test it:
public static void main(String[] args) {
CustomObj customObj = new CustomObj(123L, 11, 34, 45, 99);
CustomKey customKey = new CustomKey(123L, 11, 34, 45, 99);
CustomKey customKey2 = new CustomKey(124L, 12, 34, 45, 99);
System.out.println(customObj.equals(customKey));// This will return true since the key is same
System.out.println(customObj.equals(customKey2));// This will return false since the key is same
}