简体   繁体   中英

Java - new hashCode method

I should override with several changes the method hashCode() for a array with length 500. Each array index (for example array[499]) must contains exactly 35512 object.

I work with String of length 6 like that : "character character character number number number" (eg "ABX015"). I must write a method hasdcode for every String like it (from "AAA000" to "ZZZ999" )

I wrote this :

public int hashCode() {
return ((Math.abs(myStringName.hashCode()) %499);
}

The only problem is that I got differents values depending which index I use.

Can you help me ?

Thanks

So you're hashing 6-char String values that starts with 3 letters and end in 3 numbers. You want to create a hash for all 17576000 possible combinations and have them fall between 0 and 499, and all be equally distributed across this range of hashes. You want it so you can create an array of size 500 that counts collisions. And what you expect is array[*] = 35152 (since 17576000 / 500 = 35152).

Do I understand that correctly?

Either way, here's the easy solution I came up with:

@Override
public int hashCode() {
    int num = Integer.valueOf(myStringName.substring(3));
    return num / 2;
}

You know that the last three are going to be 0-999. Just divide that by 2 and use that as your hash.

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