Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash function to generate hash value with only 5 digits in java

Tags:

java

hash

oracle

I have used hashCode() method from String API and it is generating value as 99162322 for the below code:

String str = "hello";           
System.out.println(str.hashCode());

Is there any Java API which generate a hash value with only 5 digits (63346) like Oracle SQL as below?

select ORA_HASH('hello','99999') from dual  --63346
like image 316
Sudarsana Kasireddy Avatar asked Apr 15 '15 16:04

Sudarsana Kasireddy


People also ask

How do you create a hash function in Java?

The idea is to make each cell of hash table point to a linked list of records that have same hash function value. Let's create a hash function, such that our hash table has 'N' number of buckets. To insert a node into the hash table, we need to find the hash index for the given key.

How do you hash a number in Java?

The HashCode for an Integer can be obtained using the hashCode() method in Java. This method does not accept any parameters and it returns a hash code value of the Integer object.

How do you generate a hash value?

In Windows File Explorer select the files you want the hash values calculated for, click the right mouse button, and select Calculate Hash Value, then select the appropriate hash type from the pop-up sub-menu (e.g. MD5). The values will then be calculated and displayed.


2 Answers

Oracle's ora_hash function is designed to provide a hash code for distributing items into buckets efficiently. That makes the purpose of the function with no maximum equivalent to the purpose Java's hashCode() method.

It appears that in Oracle the maximum value argument just takes the modulus of the hash code by the maximum value + 1.

SQL> select ora_hash('hello', 49999) from dual;

ORA_HASH('HELLO',49999)
-----------------------
                  13346

In Java, to provide an equivalent value, you can obtain the remainder of dividing the hash code by that maximum value plus one.

int hash = str.hashCode() % (max + 1);  // max could be 99999

However, the hashing algorithms for String and Oracle are different, so the values will differ.

String s = "hello";
System.out.println(s.hashCode() % 100000);

Output:

62322

Also, the range of a Java hash code is that of a signed int, and the range of ora_hash is that of an unsigned integer.

like image 187
rgettman Avatar answered Sep 29 '22 02:09

rgettman


Not really sure why you need this, but you could MOD the result, for example...

String h = "blah";

int hash = h.hashCode() % 100000; // Would give numbers from 0-99999
int hash = h.hashCode() % 10000; // Would give numbers from 0-9999

I suppose you need it to return exactly the same number as the Oracle function thought right?

like image 37
BretC Avatar answered Sep 29 '22 00:09

BretC