简体   繁体   中英

How can hashing Long ids to integer ids be safe?

I just can't come up with a better solution than this.

Simple example: I have meals. Each meal has a description but those come in different languages. That is why a MealDescription consists of a primary key (MealId, LanguageId) . So far so good.

This guide here tells me that I have to implement equals() and hashCode() but is it safe to do something like this:

@Override
public int hashCode() {
    return (int) mealId.hashCode() + languageId.hashCode();
}

if mealId and languageId are actually of type Long like they have to be since they are ids?

The guide I am referring to does the same:

private String name;
private long id;
// ..
public int hashCode() {
    return (int) name.hashCode() + id; 
}

So how does that work out?

hash, in principle, is less diverse than the object. you can have two or more objects mapped to the same hash. It is even legal (though very bad) to always return 0 from hashCode()

another example, the MD5 hash is 128 bits, no matter how long the message is.

Always remember: return 0 is always a valid implementation of hashCode() . Hash codes aren't supposed to be unique, and this implementation does that just fine.

More or less, what you want from a hashCode implementation is just messing around with numbers until you get something fast to compute, int -shaped, deterministic based on the input, and is otherwise as messy as possible. This is a perfectly fine implementation.

If your mealId / languagId are Long 's why would it be a problem to use their hashCode() s? That happens every day in a lot of Java code. Hash'es are most always shorter than the objects they stem from. The thing to "hope for" is that the risk for collision is small, and that risk does not get larger or smaller by adding two hashes as you do.

So, TL;DR, yes it's safe.

Cheers,

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