簡體   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