日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

java – 比較器接口的equals方法,為什么總是安全的不覆蓋Object.equals(Object)

 印度阿三17 2019-06-27

我目前正在研究Comparator接口,并注意到在Comparator’s equals方法的文檔中,它說明了

Note that it is always safe not to override Object.equals(Object)

enter image description here

我已經(jīng)檢查了Object類中默認equals方法的實現(xiàn)

enter image description here

因此,使用equals方法的默認實現(xiàn),它只是檢查兩個實例是否指向同一個對象,因為這= = obj測試參考相等性.

但是如果我有兩個Comparator實例會發(fā)生什么,它們返回的結(jié)果是相同的,我想知道它們是否相同.如果我不重寫默認的Object的equals方法,那么無論它們返回的結(jié)果是否相等,通過使用默認的Object的equals方法,將始終返回false.那么是否仍然可以安全地不覆蓋Object.equals(Object)?

解決方法:

我想你錯誤地解釋了java doc所說的內(nèi)容:

this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator

只有當它完全是同一個對象時,默認實現(xiàn)才會返回true,根據(jù)定義,它們都表示它們(實際上是單個)提供相同的排序順序

這個定義并不意味著它會為不同的比較器返回true,即使它們提供相同的排序順序,簡單的驗證:

import java.util.Comparator;

public class TestComparator {
    static class Comparator1 implements Comparator<Integer> {
        @Override
        public int compare(final Integer o1, final Integer o2) {
            return Integer.compare(o1, o2);
        }
    }

    static class Comparator2 implements Comparator<Integer> {
        @Override
        public int compare(final Integer o1, final Integer o2) {
            return Integer.compare(o1, o2);
        }
    }

    public static void main(final String[] args) {
        final Comparator1 c1 = new Comparator1();
        final Comparator1 c11 = new Comparator1();
        final Comparator2 c2 = new Comparator2();

        System.out.println(c1.equals(c1)); // true
        System.out.println(c1.equals(c11)); // false
        System.out.println(c1.equals(c2)); // false
    }
}

如果比較器等效,則默認實現(xiàn)可以返回true,也可以返回false(如果對象不同)

請注意,doc說:

However, overriding this method may, in some cases, improve performance by allowing programs to determine that two distinct comparators impose the same order.

因此,不使用覆蓋是安全的,但僅僅保證不同但等效的比較器將被正確比較是不夠的

來源:https://www./content-1-272851.html

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多