Skip to content

Instantly share code, notes, and snippets.

@jaimemin
Created January 26, 2024 23:30
public final class PhoneNumber {
private final short areaCode, prefix, lineNum;
public PhoneNumber(int areaCode, int prefix, int lineNum) {
this.areaCode = rangeCheck(areaCode, 999, "area code");
this.prefix = rangeCheck(prefix, 999, "prefix");
this.lineNum = rangeCheck(lineNum, 9999, "line num");
}
private static short rangeCheck(int val, int max, String arg) {
if (val < 0 || val > max) {
throw new IllegalArgumentException(arg + ": " + val);
}
return (short)val;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof PhoneNumber)) {
return false;
}
PhoneNumber pn = (PhoneNumber)o;
return pn.lineNum == lineNum
&& pn.prefix == prefix
&& pn.areaCode == areaCode;
}
}
public class HashMapTest {
public static void main(String[] args) {
Map<PhoneNumber, String> map = new HashMap<>();
PhoneNumber number1 = new PhoneNumber(123, 456, 7890);
// 같은 인스턴스인데 다른 hashCode
System.out.println(number1.hashCode());
System.out.println(new PhoneNumber(123, 456, 7890).hashCode());
map.put(number1, "jaimemin");
/**
* equals가 같은데 hashcode가 매번 다를 경우
*
* get을 할 때 hashmap에 넣는 과정과 꺼내는 과정을 이해해야 함
* key에 대한 hashcode를 먼저 가져와서 hash에 해당하는 bucket에 넣고 뺀다
* hashcode가 매번 다를 경우 hashmap에는 이런 hash가 없는데?하면서 null이 나오는 것
*/
String s = map.get(new PhoneNumber(123, 456, 7890)); // null
System.out.println(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment