자바: 비교 인 터 페 이 스 를 실현 할 때 여러 가지 상황 을 전면적으로 비교 해 야 한다.

3214 단어 JAVA
자바 에서 클래스 의 사용자 정의 비교 기능 을 실현 할 수 있 습 니 다. Comparable 또는 Comparator 를 실현 할 수 있 습 니 다. 전 자 는 내부 비교 기 이 고 후 자 는 외부 비교 기 입 니 다. 그러나 어느 것 이 든 비교 방법 을 실현 할 때 여러 가지 상황 을 충분히 고려 해 야 합 니 다.
  • 비교 자가 피 비교 자 (즉, copare To 방법 중의 대상) 보다 크 면 정수
  • 로 돌아 갑 니 다.
  • 비교 자 는 피 비교 자 와 같 으 면 0
  • 으로 돌아 갑 니 다.
  • 비교 자가 피 비교 자 보다 적 으 면 마이너스 정수
  • 로 돌아간다.
    만약 그 중의 두 가지 상황 만 을 고려 했다 면 어떤 영향 이 있 었 을 까?
    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;
            }
        }
    }
    

    좋은 웹페이지 즐겨찾기