개체 equals 및 hashCode
1602 단어 HashCode
package scjp;
import java.util.HashSet;
public class WrappedString {
private String s;
public WrappedString(String s) {
this.s = s;
}
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((s == null) ? 0 : s.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;
// WrappedString other = (WrappedString) obj;
// if (s == null) {
// if (other.s != null)
// return false;
// } else if (!s.equals(other.s))
// return false;
// return true;
// }
public static void main(String[] args) {
HashSet<Object> hs = new HashSet<Object>();
WrappedString ws1 = new WrappedString("aardvark");
WrappedString ws2 = new WrappedString("aardvark");
String s1 = new String("aardvark");
String s2 = new String("aardvark");
hs.add(ws1);
hs.add(ws2);
hs.add(s1);
hs.add(s2);
System.out.println(hs.size());
}
}
이 문제는 출력이 3이다. 여기서 주로 대상의 상등성과 String의 상등의 공통점을 위해 두 문자열은null이 아니라 문자열의 서열이 상등하면true이다. 이로써 우리는 s1을 알 수 있다.equals(s2)는 사용자 정의object와 같이 equals 방법을 덮어써야 하기 때문에 3으로 출력하고 주석법 앞의 주석을 제거하면 2로 출력합니다