简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM