繁体   English   中英

计算的哈希码位于特定的值范围内?

[英]Computed hashcode to lie within a particular range of values?

我有一个 function 看起来像这样:

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
}

现在,要求是我希望此方法返回哈希码,使其在 0-10 范围内且不应超过 10。根据我的最简单方法是在返回值之前添加条件检查,然后返回根据我的意愿随机值,但这是一个最佳解决方案,还是我应该设置一个固定的“shardCount”值来实现结果?

最简单的方法是在除以10时返回余数。

代替

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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