대학 생활/JAVA
[JAVA] equals, hashCode 메서드 함께 오버라이드하기.
opid
2015. 2. 11. 18:54
equals() 와 hashCode() 는 함께 오버라이드 할 것.
자료형 |
해시 값 계산 방법 | ||
|---|---|---|---|
boolean |
(value ? 1 : 0) |
||
byte, char short, int |
(int) value |
||
float |
Float.floatToIneBits(value) |
||
double |
Double.doubleToLongBits(value) |
||
String 및 기타 객체 | "test".hashCode() | ||
package Test;
public class Test {
int intVal;
String strVal;
public Test(int intVal, String strVal) {
this.intVal = intVal;
this.strVal = strVal;
}
public int getIntVal() {
return intVal;
}
public void setIntVal(int intVal) {
this.intVal = intVal;
}
public String getStrVal() {
return strVal;
}
public void setStrVal(String strVal) {
this.strVal = strVal;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + intVal;
result = prime * result + ((strVal == null) ? 0 : strVal.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test other = (Test) obj;
if (intVal != other.intVal)
return false;
if (strVal == null) {
if (other.strVal != null)
return false;
} else if (!strVal.equals(other.strVal))
return false;
return true;
}
}
이클립스에서는 만드는 방법
단축키 Shift + Alt + S
Generate hashCode() and equals()... 선택