簡體   English   中英

比較 2 HashMap,鍵作為字符串,值作為用戶定義對象

[英]Comparing 2 HashMap with Key as String and Value as UserDefined Object

我想將布爾值輸出為 true,表示兩個地圖具有相同的鍵和值。 如果我使用 equals() 它返回 false。 我如何輸出為 true ,對象引用不同。 但是條目是相同的,我在下面有 2 張地圖

Map<String,Information> map1=new HashMap<>();
map1.put("key1", new Information("10","20","30","40"));
map1.put("key2", new Information("11","22","33","44"));
Map<String,Information> map2=new HashMap<>();
map2.put("key1", new Information("10","20","30","40"));
map2.put("key2", new Information("11","22","33","44"));

POJO 如下:帶有公共 getter 和 setter

public class Information {

private String value1;
    private String value2;
    private String value3;
    private String value4;

public Information(String value1,
                      String value2,
                      String value3,
                      String value4)
{
   this.value1 = value1;
   this.value2 = value2;
   this.value3 = value3;
   this.value4 = value4;
}
}

HashMap使用equals()來比較兩個條目。 對於HashMap<String, Information> ,它使用StringInformationequals()來確定兩個條目是否相等。 由於您的Information類沒有覆蓋Object中的equals() ,因此相等比較基於地址。

要按值比較兩個Information ,您可以在Information類中覆蓋equals()

@Override
public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    if (obj instanceof Information info) {
        return value1.equals(info.value1) &&
               value2.equals(info.value2) &&
               value3.equals(info.value3) &&
               value4.equals(info.value4);
    }
    return false;
}

你必須像這樣喂同樣的物體

    Information info1 = new Information("10", "20", "30", "40");
    Information info2 = new Information("11", "22", "33", "44");
    Map<String, Information> map1 = new HashMap<>();
    map1.put("key1", info1);
    map1.put("key2", info2);
    Map<String, Information> map2 = new HashMap<>();
    map2.put("key1", info1);
    map2.put("key2", info2);

    System.out.println(map2.equals(map1));// prints true

您正在比較信息類的兩個不同實例,因此您得到了錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM