电竞比分网-中国电竞赛事及体育赛事平台

分享

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類中默認(rèn)equals方法的實(shí)現(xiàn)

enter image description here

因此,使用equals方法的默認(rèn)實(shí)現(xiàn),它只是檢查兩個(gè)實(shí)例是否指向同一個(gè)對(duì)象,因?yàn)檫@= = obj測(cè)試參考相等性.

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

解決方法:

我想你錯(cuò)誤地解釋了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

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

這個(gè)定義并不意味著它會(huì)為不同的比較器返回true,即使它們提供相同的排序順序,簡(jiǎn)單的驗(yàn)證:

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
    }
}

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

請(qǐng)注意,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

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

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多