Search code examples
javaarrayshashcodegethashcodemodulo

Computed hashcode to lie within a particular range of values?


I have a function which looks like this:

public int getHashcode(int shardCount){

    String personid = "<some long string value>";
    String servicedate = "2019-12-22T01:31:30.000Z";
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
    return hashCodeBuilder.append(personid).append(servicedate).toHashCode() % shardCount;

//the shard count key comes in from a config file and has various values
// like 2,5,15,25 etc depending on some criteria
}

Now, the requirement is that I want this method to return the hashcode such that it falls in the range of 0-10 and should not exceed 10. Simplest way according to me, is adding a conditional check before returning the value and then return a random value as per my wish, but is that an optimal solution to this, or should I put a fixed "shardCount" value to achieve the result?


Solution

  • The simplest way is to return the remainder when divided by 10.

    Replace

    return hashCodeBuilder.append(personid).append(servicedate).toHashCode() % shardCount;
    

    with

    return (hashCodeBuilder.append(personid).append(servicedate).toHashCode() % shardCount) % 10;