자바: 비교 인 터 페 이 스 를 실현 할 때 여러 가지 상황 을 전면적으로 비교 해 야 한다.
3214 단어 JAVA
만약 그 중의 두 가지 상황 만 을 고려 했다 면 어떤 영향 이 있 었 을 까?
Bad Case 는 아래 의 실현 을 고려 하여 TreeSet 이나 TreeMap 의 contains Key 를 호출 할 때 어떤 영향 을 미 칩 니까?
@Data
@EqualsAndHashCode
class ImgSize implements Comparable {
private int width;
private int height;
public ImgSize(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public int compareTo(ImgSize obj) {
if (this.width < obj.width) {
return -1;
} else if (this.height < obj.height) {
return -1;
} else {
return 1;
}
}
}
Map pics = new TreeMap<>();
pics.put(new ImgSize(3,4), "Pic_A");
pics.put(new ImgSize(1,3), "Pic_B");
pics.put(new ImgSize(1,2), "Pic_C");
for(Map.Entry entry:pics.entrySet()) {
System.out.println(entry);
}
System.out.println(pics.containsKey(new ImgSize(1,2)));
//
ImgSize(width=1, height=2)=Pic_C
ImgSize(width=1, height=3)=Pic_B
ImgSize(width=3, height=4)=Pic_A
false
정렬 기능 이 구현 되 었 음 에 도 불구 하고 containsKey 방법 으로 돌아 온 false 는 왜 일 까?그것 의 실현 을 보아 도 무방 하 다
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
final Entry getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable super K> k = (Comparable super K>) key;
Entry p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
containskey 는 hashCode 와 equals 방법 에 따라 이 루어 진 것 이 라 고 생각 했 습 니 다. lombok 주 해 는 이 두 가지 방법 을 실 현 했 습 니 다. 그러나 containskey 는 실제 비교 기 에 따라 이 루어 진 것 입 니 다. 사용자 정의 비교 기 에서 같은 실현 이 없 으 면 containskey 는 예상 한 결 과 를 정확하게 되 돌려 주지 않 습 니 다.
수정 하 다.
@Data
@EqualsAndHashCode
class ImgSize implements Comparable {
private int width;
private int height;
public ImgSize(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public int compareTo(ImgSize obj) {
if (this.width < obj.width) {
return -1;
} else if (this.width == obj.width) {
return (this.height < obj.height ? -1:(this.height == obj.height ? 0 : 1));
} else {
return 1;
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JAVA 객체 작성 및 제거 방법정적 공장 방법 정적 공장 방법의 장점 를 반환할 수 있습니다. 정적 공장 방법의 단점 류 공유되거나 보호된 구조기를 포함하지 않으면 이불류화할 수 없음 여러 개의 구조기 파라미터를 만났을 때 구축기를 고려해야 한다...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.