r/javahelp • • Mar 07 '22

HashCodes... Yes... we know... "equal Strings == Equal hashCodes!!1!".

Of course, if 2 strings are equal the hashcode will be the same,

Of course, if you use the hashCode as a persistent ID (for Database or whatever) is a bad idea, but I feel these obviously bad implementations of hashCode muddle every valid implementation the hashCode functionality may have.

What about the innate hashCode of a Java object, No one seems to succinctly address this, do the JVM even keep a registry??

If we need to "care about the hashcode" and "stop using it as an object id", then Why do we even use HashMaps or Sets, do they do something to prevent collisions? , and if they do, why isn't that handled at object instantiation...

By definition if the hashCode() method of an object is as unsafe as it is meant to be, then all those classes should also be unsafe.

Most of the claims of hashCodes being bad as an id, are so vague and allude to the same two examples, that one is left completely unconvinced about it, why would sun make something so untrustworthy?

The only... only believable claim I've seen online, is the one based on the birthday paradox which states that once there are 77 163 objects you have a 50% chance of getting 2 equal hashCodes.

Again, this is a room full of guests, what if within that room you have a bathroom??? What are the chances of getting 2 random people in that bathroom with the same birthday, I bet hashCode is extremely useful on that bathroom alone???

Does this mean that Java becomes completely useless once 77 163 items are created?

Do the JVM even keep a registry of each hashCode created so that it keeps this 50% in check and keeps the chances low??

0 Upvotes

11 comments sorted by

•

u/AutoModerator Mar 07 '22

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

8

u/philipwhiuk Employed Java Developer Mar 07 '22

What?

The purpose of hashCode is to roughly spread objects equally across a distribution. The fewer the collisions the better.

In the case of a collision a hashSet then stores colliding objects as a list and uses the equality function to check if it’s stored.

A good hashCode function and no collisions results in O(1) search performance. A bad hashCode function where everything has the same hashCode results in O(n) performance.

Yes collisions are inevitable if you have enough objects. The aim is to minimise them.

1

u/DelarkArms Mar 07 '22

Thank you.

What I get from your answer is that there is no reliable way of defining uniqueness without a diminishing in performance, hence the need to check for collisions on a case-by-case basis.

Your answer helped me reflect that maybe I was focusing on the wrong thing, it seems that what I need is this:

String uniqueID = UUID.randomUUID().toString();

The diminishing in performance seems to be unavoidable in this case.

2

u/[deleted] Mar 07 '22

Me again

Last night I went to sleep with your question and I'm kind of an obsessive person.

It looks that you're looking for an efficient way to check entity Identity.

For that, I would point you to some concepts of DDD.

Most of real world entities have a natural identifier, SSN for people, ISBN for books, serial numbers for hardware, etc.

You can use those as fields to check identity and as PK on database.

If you have two instances of Person with the same SSN, they ARE the same, no matter if it's named John on one and Johny on other.

Of course, I might just be overthinking all this.

1

u/DelarkArms Mar 07 '22 edited Mar 07 '22

Thanks for your reply I came across a response from mr. Jon Skeet

is just a matter of comparing the references in a bitwise fashion - checking whether or not they consist of the same bytes.

My aim was to mimic the == operator without having to cache the reference, and instead dereference the value that the JVM was using at the moment of "==" comparison.

(This was what my "two people with the same birthday in the same room, at a party with 77 163 guests" sentence was alluding to)

The misunderstanding (MY misunderstanding) was that hashCode (identityHashcode to be more precise) was being used under the hood to check for reference address check... it seemed reasonable...

By doing this I was also attempting to assign an int ID field at the moment of initialization (To prevent re-computations).

It seems accessing the inner workings of object reference comparison is not doable, so I better stick to passing the whole reference instead.

As for your advice, it is a really good one. I do manually check for Object contents, that is the only way when dealing with persistent memory.

0

u/AutoModerator Mar 07 '22

You seem to try to compare String values with == or !=.

This approach does not work reliably in Java as it does not actually compare the contents of the Strings. Since String is an object data type it should only be compared using .equals(). For case insensitive comparison, use .equalsIgnoreCase().

See Help on how to compare String values in our wiki.


Your post/comment is still visible. There is no action you need to take.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

6

u/[deleted] Mar 07 '22 edited Mar 07 '22

I might be misunderstanding you (it's been a long day to me), but I think you got it backwards.

The contract says that if two objects are equal then their hash code must be the same.

But it's not required that if two objects have the same hash code then they must be equal.

It goes only one way and hash code is not a replacement for equality.

2

u/D0CTOR_ZED Mar 07 '22

What are you trying to achieve? You were taking about hashing functions but now are using a random uuid. Hashing makes sense if you can recreate the same hash. Random makes sense if you don't have to recreate it.

2

u/8igg7e5 Mar 07 '22

Hashcodes are expected to collide and are not 'tracked' at all by the JVM (because it's perfectly fine to have two objects with the same hashcode). Given there's only ~4 billion (32bit) possible values (which for many business problem is not actually very large), even if the JVM did try to make them unique, it would quickly hit limitations.

UUID is intended as an identity. It has an immensely larger pool of unique values (about 120 bits for random UUIDs IIRC).

Note: The UUID is better represented as two longs (128 bits) (as it is internally to the UUID type). Don't convert it to String (288 bits in UTF-8) to store/use it unless the storage medium is text-based (and parse it back into a UUID on load). Several data-stores have native UUID support.

3

u/D0CTOR_ZED Mar 07 '22

HashMaps and sets handle collections. The only danger of using hashes is when you don't know how to implement their use. The people who make these libraries know what they are doing.

3

u/morhp Professional Developer Mar 07 '22

Do the JVM even keep a registry of each hashCode created

No, of course not. You can very easily create two objects that aren't equal but have the same hashcode. If java wanted, it could've implemented Object.hashCode as return 13; and everything would still work fine (only with much worse performance).

HashCodes are a performance optimization so HashMaps and similar data structures can sort objects into different buckets, they should never be used as an object id or something like that. And collisions aren't a huge problem other than that performance may suffer a bit.