我有一个函数,看起来像这样:
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“值来实现结果?
发布于 2020-05-10 23:11:29
最简单的方法是返回除以10
后的余数。
替换
return hashCodeBuilder.append(personid).append(servicedate).toHashCode() % shardCount;
使用
return (hashCodeBuilder.append(personid).append(servicedate).toHashCode() % shardCount) % 10;
https://stackoverflow.com/questions/61714168
复制相似问题