一個由List.removeAll()失效引發的思考

前言:

本來以為是個錯誤使用的問題,稍微那么深究一下,發現腦海中,關于這個部分的知識庫存已經告急了,可不能啊。

removeAll() 失效重現

今天做一個批量刪除的功能,我使用了 List.removeAll()這個方法,但是該代碼執行前后,被操作的列表的 size 并沒由發生改變。

排查了一下,是因為兩個列表中存儲對象不同的原因。

為了更加清楚的理解,我寫了簡單的小例子,浮現了錯誤的場景:

實體類:

public class Bean {

    private int id;
    private String name;
    private String address;

    public Bean(int id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }
}

構建場景:


     ArrayList<Bean>  allStudents = new ArrayList<>();
     ArrayList<Bean>  boyStudents = new ArrayList<>();


     for (int i = 0; i < 10 ; i++) {
         Bean  bean = new Bean(i,"name is "+i,"address is "+i);
         allStudents.add(bean);

     }


     for (int i = 0; i < 5 ; i++) {
         Bean  bean = new Bean(i,"name is "+i,"address is "+i);
         boyStudents.add(bean);

     }

      System.out.println("allStudents.size()------before-------------->"+allStudents.size());
      System.out.println("remove result : "+allStudents.removeAll(boyStudents));
      System.out.println("allStudents.size()-------after-------------->"+allStudents.size());




輸出結果是:


allStudents.size()------before-------------->10
remove result : false
allStudents.size()-------after-------------->10

但是,換 String 對象執行 removeAll() 竟然可以成功!

因為操作對象不同,這是一個很簡單的原因,但是接下來要實驗的另一個小例子,絕對讓你非常吃驚,我們講Bean 替換成 String 字符串試一下。


       ArrayList<Bean>  allStudents = new ArrayList<>();
       ArrayList<Bean>  boyStudents = new ArrayList<>();
       for (int i = 0; i < 10 ; i++) {
           Bean  bean = new Bean(i,"name is "+i,"address is "+i);
           allStudents.add(bean);

       }


       for (int i = 0; i < 5 ; i++) {
           Bean  bean = new Bean(i,"name is "+i,"address is "+i);
           boyStudents.add(bean);

       }

       System.out.println("allStudents.size()------before-------------->"+allStudents.size());
       System.out.println("remove result : "+allStudents.removeAll(boyStudents));
       System.out.println("allStudents.size()-------after-------------->"+allStudents.size());




輸出結果是 :

allStudents.size()------before-------------->10
remove result : true
allStudents.size()-------after-------------->5

揭開這一切的面紗

從打印結果很明白的看到,removeAll() 成功執行。String也是對象,為什么會這樣?代碼不會說謊,我們去源碼中去尋找答案。
從源碼中發現,ArrayList 執行 removeAll() 方法流程如下圖所示:

removeAll流程圖

通過控制變量法分析,很容易就聚焦到 equals()這個方法,這個方法是 Object 的方法,默認實現是比較對象在內存的地址。

public boolean equals(Object obj) {
       return (this == obj);
   }

再看一下 String 中 equals() 方法,重寫了 Object 的這個方法,不再是比較地址,而是比較字符串是否相同。


public boolean equals(Object anObject) {
     if (this == anObject) {
         return true;
     }
     if (anObject instanceof String) {
         String anotherString = (String) anObject;
         int n = count;
         if (n == anotherString.count) {
             int i = 0;
             while (n-- != 0) {
                 if (charAt(i) != anotherString.charAt(i))
                         return false;
                 i++;
             }
             return true;
         }
     }
     return false;
 }


這樣的話,引發了一個思考,也就是說,如果自定義對象,重寫 equals() 中的實現,也是可以實現非相同對象的情況下,成功 removeAll()的。這里我用 上面例子的 Bean 實體類簡單實驗一下:

public class Bean {

    private int id;
    private String name;
    private String address;

    public Bean(int id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Bean bean = (Bean) o;

        if (id != bean.id) return false;
        if (!name.equals(bean.name)) return false;
        return address.equals(bean.address);

    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + name.hashCode();
        result = 31 * result + address.hashCode();
        return result;
    }
}


再次執行第一個例子的程序,ArrayList<Bean> 成功 removeAll,打印信息如下:

allStudents.size()------before-------------->10
remove result : true
allStudents.size()-------after-------------->5

重寫 equals() 方法一定要符合規范!

但是這里我們要特別注意的是,當我們重寫 equals() 方法的時候,一定要遵守它的規范,否則在程序使用中,使用錯誤實現 equals() 的類時可能出現無法預料的問題,而且很有可能,找了很久都定位不到問題在哪!,想想都后背發冷。

以下是 Object 中 equals()的方法說明注釋,絕對原汁原味!但是我相信肯定有人看了一遍還是不知道說的啥,非常正常,我看兩遍也是,英語渣沒辦法,只能花更多時間去理解它,因為真的真重要。


/**
 * Indicates whether some other object is "equal to" this one.
 * <p>
 * The {@code equals} method implements an equivalence relation
 * on non-null object references:
 * <ul>
 * <li>It is <i>reflexive</i>: for any non-null reference value
 *     {@code x}, {@code x.equals(x)} should return
 *     {@code true}.
 * <li>It is <i>symmetric</i>: for any non-null reference values
 *     {@code x} and {@code y}, {@code x.equals(y)}
 *     should return {@code true} if and only if
 *     {@code y.equals(x)} returns {@code true}.
 * <li>It is <i>transitive</i>: for any non-null reference values
 *     {@code x}, {@code y}, and {@code z}, if
 *     {@code x.equals(y)} returns {@code true} and
 *     {@code y.equals(z)} returns {@code true}, then
 *     {@code x.equals(z)} should return {@code true}.
 * <li>It is <i>consistent</i>: for any non-null reference values
 *     {@code x} and {@code y}, multiple invocations of
 *     {@code x.equals(y)} consistently return {@code true}
 *     or consistently return {@code false}, provided no
 *     information used in {@code equals} comparisons on the
 *     objects is modified.
 * <li>For any non-null reference value {@code x},
 *     {@code x.equals(null)} should return {@code false}.
 * </ul>
 * <p>
 * The {@code equals} method for class {@code Object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * Note that it is generally necessary to override the {@code hashCode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashCode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @param   obj   the reference object with which to compare.
 * @return  {@code true} if this object is the same as the obj
 *          argument; {@code false} otherwise.
 * @see     #hashCode()
 * @see     java.util.HashMap
 */
public boolean equals(Object obj) {
    return (this == obj);
}


equals 方法實現的時候必須要滿足的特性:

1.(reflexive)自反性:

對于任何非 null 的引用值 x,x.equals(x) 必須為 true;

2.(symmetric)對稱性:
對于任何非 null 的引用值 x,y,當且僅當 y.equals(x) 返回 true 時,x.equals(y) 也要返回 true 。

3.(transitive)傳遞性:
對于任何非 null 的引用值 x,y,z, 如果 x.equals(y) 返回 true,y.equals(z) 返回 true,那么 x.equals(z) 一定要返回 true。

4.(consistent)一致性:
對于任何非 null 的引用值 x,y,只要 equals() 方法沒有修改的前提下,多次調用 x.equals(y) 的返回結果一定是相同的。

5.(non-nullity)非空性
對于任何非 null 的引用值 x,x.equals(null) 必須返回 false。

這些特性約束我們重寫 equals()的時候,寫條件判斷一定要謹慎,下面是提供的一個模版:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    (MyClass) myclass = (MyClass) o;
    if (this.xx != bean.myclass.xx) return false;
    return myclass.equals(myclass.xx);

}

重要!覆蓋 equals 時,一定要同時覆蓋 hashCode

這樣做的目的是保證每一個 equals()返回 true 的兩個對像,要有兩個相同的 hashCode 。

在上面演示的例子中,不覆蓋 hashCode ,equals 方法表現的也很好,調用 List.removeAll 也能成功執行。看似是沒有什么問題,但是當我們試圖使用 hashMap 做存取操作的時候,就會出現問題。


HashMap<Bean,String> allStudents = new HashMap<>();

for (int i = 0; i < 10 ; i++) {
    Bean  bean = new Bean(i,"name is "+i,"address is "+i);
    allStudents.put(bean,"i :"+i);

}
Bean bean = new Bean(1,"name is 1","address is 1");

System.out.println(" allStudents.get(bean)----------------------->"+ allStudents.get(bean));


輸出結果:

Bean 中不正確覆蓋 hashCode(),取不到值:

allStudents.get(bean)----------------------->null

Bean 中正確覆蓋 hashCode(),能取到值:

allStudents.get(bean)----------------------->i :1

原因在于,HashMap 執行 get() 操作的時候是通過散列碼,也就是對象的 HashCode 來搜索數據的。所以,當不重寫 hashCode() 方法或者重寫的不規范的時候,就會出現這樣的問題。
使用散列碼判斷對象的,有 HashMap ,HashSet,HashTable 等,因此,覆蓋 equals() 時,一定要同時覆蓋 hashCode()。

快速生成euqals() and hashCode()!

看到上面的解釋,估計大家都感覺覆蓋這倆方法的時候都有點害怕了,但是告訴大家一個好消息,Android Studio 有這兩個方法的快速生成模版,使用方法是 右鍵->generate->euqals() and hashCode(),也可以直接使用快捷鍵 command+N ->euqals() and hashCode()。

快速生成equals和hashCode

最后

到這里,我想到,一個在面試的時候,經常被問到的 java 基礎題:

java 中 == 和 equals 和 hashCode 的區別?

我想現在,如果再被問到這個問題,我肯定可以比之前回答的要好一點了。

java 中有兩種類型,值類型和引用類型。其中,== 值類型和引用類型都可以運算,equals 和 hashCode 是引用類型特有的方法。

對于值類型,== 比較的是它們的值,對于引用類型,== 比較的是兩者在內存中的物理地址。

equals() 是 Object 類中的方法,默認實現是使用 == 比較兩個對象的地址,但是在一些子類,例如 String,Float,Integer 等,它們對 equals進行覆蓋重寫,就不再是比較兩個對象的地址了。

hashCode() 也是 Object 類的一個方法。返回一個離散的 int 型整數。在集合類操作中使用,為了提高查詢速度。

當覆蓋 equals() 的時候,一定要同時覆蓋 hashCode(),保證 x.equals(y) 返回為 true 的時候,x,y 要有相同的 HashCode 。

回答完畢。

參考資料

Effective Java 中文版第二版

最后

剛剛開通了個人微信公眾號,最新的博客,好玩的事情,都會在上面分享,歡迎關注^ o ^。

微信公眾號
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,048評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,414評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,169評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,722評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,465評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,823評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,813評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,000評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,554評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,295評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,513評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,722評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,125評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,430評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,237評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,482評論 2 379

推薦閱讀更多精彩內容