簡體   English   中英

HashMap 的自定義哈希碼/等於操作

[英]Custom hashcode/equals operation for HashMap

是否有 HashMap 類(或 Map 接口)的實現,它允許我使用備用哈希碼和等於操作......類似於如何使用 Collections.sort(列表,比較器)。

如果可能的話,我想避免創建一個提供所需哈希碼和等於操作的密鑰包裝器。


在我的情況下,為什么我需要這樣的場景之一:

在我的 Web 應用程序中,對於每個請求,我加載位置/ISP 和其他數據。 在代碼的不同部分(在我的服務層和存儲庫層中),我已經“最小化”了特定於其要求的緩存。

這是一個簡化的代碼示例:

class GeoIpData{
    private String countryName;
    private String state;
    private String city;
    private String isp;
    @Override
    public int hashCode() {
        //countryName hashCode
        //state hashCode
        //city hashCode
        //isp hashCode
    }
    @Override
    public boolean equals(Object obj) {
        // compare countryName
        // compare state
        // compare city
        // compare isp
    }
}

 Map<GeoIpData,#Type1> fullCache = ... //This cache needs to be unique per countryName,state,city and isp
 Map<GeoIpData,#Type2> countryCache = ... //This cache needs to be unique per countryName
 Map<GeoIpData,#Type2> ispCache = ... //This cache needs to be unique per countryName,isp

為了實現這一點,上述 3 個映射需要 3 個不同的哈希碼和 equals 方法。

fullCache:
hashCode -> GeoIpData.hashCode();
equals   -> GeoIpData.equals(Object obj);

countryCache:
hashCode -> {countryName hashCode }
equals   -> {compare countryName }

ispCache:
hashCode -> {countryName hashCode & isp hashCode }
equals   -> {compare countryName & compare isp hashCode }

GNU Trove允許您為特定的 TObjectHashingStrategy 提供您自己的哈希和等於 TCustomHashMap 的函數。

最初的 Java API 將equals / hashCode行為限制為類型(類),因為那時他們還沒有 lambda。

為了重用現有的 API / 實現 - 制作臨時密鑰:

public CountryKey {
    private String country;
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof CountryKey)) { return false; }
        CountryKey that = (CountryKey) obj;
        return this.country.equals(that.country);
    }
    @Override int hashCode() {
         return country.hashCode();
    }
}

或包裝:

public CountryKey {
    private GeoIpData holder;
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof CountryKey)) { return false; }
        CountryKey that = (CountryKey) obj;
        return this.holder.getCountry().equals(that.holder.getCountry());
    }
    @Override int hashCode() {
         return holder.getCountry().hashCode();
    }
}

並為鍵編寫輔助構造函數:

public class GeoIpData {
     public CountryKey buildCountryKey() {
          return new CountryKey(this.country);
     }
}

暫無
暫無

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

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