Custom hashcode / equals for HashMap

Is there an implementation of the HashMap class (or map interface) that will allow me to use an alternative hash code and equal operations ... Just like collections of the same type can be sorted in several ways using Comparator in Collections.sort (list, comparator )

I would like, if possible, to avoid by creating a key wrapper that provides the required hash code and equal operation.


In my case, one of the scenarios is why I need something like this:

In my web application, for every request, I upload Location / ISP and other data. In different parts of the code (in the service and repository layers), I have "minimized" caches specific to its requirements.

Here is an example of simplified code:

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

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 }
+5
1

GNU Trove TObjectHashingStrategy - TCustomHashMap.

+7

All Articles