DEV Community

Cover image for Hash strings to INT using Java
James Moberg
James Moberg

Posted on

Hash strings to INT using Java

I'm not sure where I previously learned about the Java hashCode() method for strings, but it enabled us to quickly assign a unique-ish numerical hash from a textual product configuration and enabled us to search, group & report data where it would have been very difficult otherwise.

The hashCode() method works in Adobe ColdFusion 8-2021. I also tested it using CFTry.com and Railo + Lucee4 worked, but Lucee5 didn't return anything so I'm not sure if it works or not.

Here's the gist:
https://gist.github.com/JamoCA/e94b1100932db2c02b18eb11afc56079

Top comments (3)

Collapse
 
bennadel profile image
Ben Nadel

I'm not a Java developer (though I do dip-down into the Java layer from CFML quite often); so, what I'm about to say may be completely wrong; but, I believe I read somewhere that the hashCode isn't necessarily guaranteed to be consistent over time for the same values. Meaning, the underlying algorithm may change with versions of Java. That said, I'm seeing conflicting things in Google about this. Some say that Strings are special case where the algorithm has been codified to be unique; and, some places saying that you should never depend on consistency across executions of the application.

But, I really don't know what I'm talking about - so only take that as something to consider, not something that is fact :D

Collapse
 
gamesover profile image
James Moberg

I checked the application that we used this with and the hashCode values have remained consistently generated since initially used in 2018.

I tested on TryCF.com and discovered that Railo, Lucee 4.5-5 & ColdFusion 10-2021 all return consistent results when passing the same text string.

Collapse
 
bennadel profile image
Ben Nadel

Ok cool -- sorry to cause any momentary panic there. I'm glad I was incorrect in my understanding of things I've read in the past.