Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
n位的Java字符串哈希代码?_Java_String_Hashcode - Fatal编程技术网

n位的Java字符串哈希代码?

n位的Java字符串哈希代码?,java,string,hashcode,Java,String,Hashcode,我试图从Java中的字符串中获取ID,我想我会使用hashcode(是的,两个字符串可以有相同的hashcode,但我可以接受这种可能性很小)。我希望这个ID最多有4个数字。可能吗 这是字符串默认哈希代码实现: public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0;

我试图从Java中的字符串中获取ID,我想我会使用hashcode(是的,两个字符串可以有相同的hashcode,但我可以接受这种可能性很小)。我希望这个ID最多有4个数字。可能吗

这是字符串默认哈希代码实现:

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}
public int hashCode(){
int h=散列;
如果(h==0&&value.length>0){
char val[]=值;
for(int i=0;i

我可以重写它以生成一个4位数的散列吗?

一个简单的技巧是只取最后四位数:

private static int myHash(String s) {
    return s.hashCode() % 10000;
}
编辑:
正如@Holger所评论的,
hashCode()
可能返回负值。如果要求返回四位正整数,则可以取绝对值:

private static int myHash(String s) {
    return Math.abs(s.hashCode() % 10000);
}

返回h%10000
;应该像你可以有任何数字表示为4位数字。剩下的。当然,您可以
@重写任何继承的非final或private方法。但是,将散列码长度减少到4位有什么意义?@IlyaBursov除了
h
可以是负的…@shmosel模块后不能是最小值为什么
静态
?@Nikolas为什么不呢?当然,你现在只有10000个has码值,所以冲突的概率比以前高得多,@尼古拉斯又来了,为什么不呢?您在这里没有使用任何实例成员,那么为什么在堆栈中不必要地推送
this
指针呢?@Nikolas OP的代码示例是一个实例方法,因为。(
String
是最后一个类,因此我们不是在讨论扩展和重写
hashCode
,也不应该像这样重写
hashCode
,即使在我们可以的情况下,因为Liskov替换原则和一般的合同义务。)恕我直言,你的批评没有多大意义。像这样的实用方法通常是静态的。