equals methodは same valueを判定
multi field classは、自分でequals methodをoverrideする。
また、hashcodeは、
equals method is trueの場合、same hashcodeというルールがあるため
equals method override のタイミングで hashcode() method overrideする
下記はnetbeansでgenerateしたequals, hashcode。
class Value {
String str;
int i;
public Value(String str, int i) {
this.str = str;
this.i = i;
}
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.str);
hash = 83 * hash + this.i;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Value other = (Value) obj;
if (this.i != other.i) {
return false;
}
return Objects.equals(this.str, other.str);
}
public Value(String str) {
this.str = str;
}
}
public class Outer {
public static void main(String[] args) {
Value v1 = new Value("A",1);
Value v2 = new Value("B",1);
Value v3 = new Value("A",2);
Value v4 = new Value("A",1);
System.out.println(v1.hashCode());
System.out.println(v2.hashCode());
System.out.println(v3.hashCode());
System.out.println(v4.hashCode());
System.out.println(v1.equals(v2));
System.out.println(v1.equals(v3));
System.out.println(v1.equals(v4));
}
}
53619
53702
53620
53619
false
false
true