Hashing,hashcode
can anyone help me to understand hashing,hashcode as such related to collections..
If you haven't got the hang of [url http://google.com/]Google then it might be beyond you. But you could try searching - there or within these forums.
PS Threads within these forums like [url http://forum.java.sun.com/thread.jsp?forum=24&thread=547010&tstart=0&trange=30]this one would help - you obviously looked really hard for some help here.
Dave.
Similar Messages
-
What will be the output and why
Hi All,
Can anyone help me in this.
package javatests.test;
import java.util.HashMap;
import java.util.Map;
public class CopyOfHashFunction1 {
private int hashCode;
public static void main(String[] args) {
Map hashTable = new HashMap();
String key1 = new String("a");
String key2 = new String("a");
System.out.println(key1.hashCode());
System.out.println(key2.hashCode());
System.out.println(key1 == key2);
hashTable.put(key1, 1);
hashTable.put(key2, 2);
System.out.println("Size = " + hashTable.size());
System.out.println("Value when key1 is searched:"+hashTable.get(key1));
System.out.println("Value when key2 is searched:"+hashTable.get(key2));
}Output:
97
97
false
Size = 1
Value when key1 is searched:2
Value when key2 is searched:2I feel there should be two entries in the HashTable, because when putting the second entry in the HashTable hash collision will happen and equals() method of String will be called. As the equals() method is returning false because the object references are different so HashTable should make another entry in the same bucket.
Please let me know the answer.
Thanks
JitendraYes you are right jverd because the code in String.java is like, so it used to compare the string character by character.
854 public boolean equals(Object object) {
855 if (object == this) {
856 return true;
857 }
858 if (object instanceof String) {
859 String s = (String) object;
860 int hash = hashCode; // Single read on hashCodes as they may change
861 int shash = s.hashCode;
862 if (count != s.count || (hash != shash && hash != 0 && shash != 0)) {
863 return false;
864 }
865 for (int i = 0; i < count; ++i) {
866 if (value[offset + i] != s.value[s.offset + i]) {
867 return false;
868 }
869 }
870 return true;
871 }
872 return false;
873 } -
Hello,
I want to be able to drag a component within a panel with the goal of repositioning it. Acutally, I want to drop one component on top of another and then swap their positions.
I have created a Transferable so that when the drop occurs, the drop target can get the source component where the drag started in order to do the swap. When the drop ocurrs, I want to get the parent container of the source component.
However, instead of getting a reference to the original source component, I seem to be getting a copy (different hash codes). And when I call sourceComponent.getParent(), I get back a null.
Is there some way to use the Transferable interface to pass the original object instead of a copy?
Here is my Transferable implementation for a swappable Component:
====================================================
// TransferableComponent
package dndcomponent2;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import javax.swing.JComponent;
/** TransferableComponent
* Wrap a JComponent in a Transferable so can pass it to drop target
* when doing drag and drop
class TransferableComponent implements Transferable
private JComponent component = null; // the component being dragged/dropped, must be serializable
public static DataFlavor componentFlavor = new DataFlavor(JComponent.class, "TransferableComponent");
private static DataFlavor[ ] supportedFlavors = {componentFlavor};
TransferableComponent(JComponent comp)
component = comp;
public DataFlavor[] getTransferDataFlavors( )
return supportedFlavors;
public boolean isDataFlavorSupported(DataFlavor flavor)
for(int i = 0; i < supportedFlavors.length; i++)
if(supportedFlavors.equals(flavor))
return true;
return false;
* The object returned by this method must be Serializable so we use a
* JComponent instead of a straight Component
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
if(flavor.equals(componentFlavor))
return component;
return null;
========================================================
and here is how I instantiate it when the drag starts:
========================================================
public void dragGestureRecognized(DragGestureEvent dge)
System.out.println("DndLabel.dragGestureRecognized source hash = " + hashCode());
dge.startDrag(DragSource.DefaultLinkDrop, // cursor
new TransferableComponent(this), // data
new DndLabelDragSourceListener( )); // drag source listenerHi,
Let's me close this thread. The problem is that we create the DataFlavor by DataFlavor(<Class>,<String>). I don't know why a copy is returned rather than a reference;
If we use DataFlavor(DataFlavor.javaJVMLocalObjectMimeType) then the reference is returned. -
Hash-based collections vs. mutable hashcodes
I've been getting ConcurrentModificationExceptions on HashTables (derivatives) in a single-threaded app that does no overt mods to the collection being iterated. The algorithm is a classic Observer, iterating all listeners on an event. These listeners are rather heavyweight classes with hashcode() (along with equals()) essentially calculating the current object internal state, which is mutable.
What I think is going on is that during an event (iteration over the set) a listener state may change, resulting in a changed hashcode(). While this doesn't overtly modify the collection, it may modify something like the internal ordering. i.e. the "old" object would appear to have disappeared since it can no longer be resolved with its current hashcode. Can anyone confirm that this is indeed a possible phenomenon? If so, it raises an interesting general issue.
Should hashcode() and equals() be built on an immutable subset of state? Assuming logical identity is desirable (i.e. state matters to equality), and hashcode should reflect the result of equals (re: Josh Bloch in EJ (2nd) Item# 8), this seems to dictate that such objects are not viable elements of a hash-based collection. Discussion?jverd wrote:
796912 wrote:
Should hashcode() and equals() be built on an immutable subset of state? hashCode() should, yes. Or, if it's mutable, then when using a hash-based collection you have to remove and re-add after a change, or possibly remove, change, re-add. Additionally, there's the iteration gotcha that you found that prompted this thread.you definitely have to remove before you change, otherwise remove won't work.
equals() shouldn't matter. Changing an object's hash can change which bucket it's in, and that's why things get screwed up. The equals() comparison comes into play when doing a linear search of that bucket, so changing state that contributes to equals won't hurt that. not entirely true. changing equals could change the validity of the uniqueness of the set. if you change the equals criteria of an object already in the set so that it is now equal to another object in the set, the set is no longer valid. while this may not break quite as spectacularly as changing the hashcode, it can still do interesting things. for instance, if you add another element such that the hashmap decides to re-hash, one of your now duplicate elements will be silently dropped on the floor. long answer short, don't change hashcode or equals.
However, in a SortedSet or SortedMap, changing state that contributes to equals() could lead to problems, so the same remove/re-add rules would apply.nope, sorted collections don't use hashcode or equals, they use compareTo/compare. but, the same rules certainly apply to the comparison criteria for the given sorted collection. -
Two objects created at the same time with the same hashcode
We have this object with the following constructor:
2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(3)(pid:24312)] INFO com.intel.swiss.sws.netstar.application.caching.framework.data
set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
/d81], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0
2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(5)(pid:24315)] INFO com.intel.swiss.sws.netstar.application.caching.framework.data
set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
/d31], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0Note that two objects are created by different threads with exactly the same hash code. Any idea if/how this is possible?isocdev_mb wrote:
The last part definitely suggests already that relying on uniqueness is incorrect. Hash codes are very often equal on distinct objects, viz. new String("java").hashCode == new String("java").hashCode(). Use a class level counter as suggested earlier.For that case we would of course expect the hashCodes to be equal, since the objects are equal. But even in the case of non-equal objects that don't override hashCode, you can still get the same value. Or, for that matter, non-equal objects that do override it. There are 2^32 possible hashCode values. There are 2^64 possible Long values. That means that there are 2^32 Longs that have a hashCode of 1, 2^32 Longs that have a hashCode of 2, etc.
And for non-equal objects...
package scratch;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
public class HashCodeIsNotUnique {
public static void main(String[] args) throws Exception {
Map<Integer, Integer> hashCodeCounts = new HashMap<Integer, Integer>();
int numObjects = 10000;
for (int i = 0; i < numObjects; i++) {
Object obj = new Object();
int hashCode = obj.hashCode();
if (!hashCodeCounts.containsKey(hashCode)) {
hashCodeCounts.put(hashCode, 0);
hashCodeCounts.put(hashCode, hashCodeCounts.get(hashCode) + 1);
for (Map.Entry<Integer, Integer> entry : hashCodeCounts.entrySet()) {
int key = entry.getKey();
int value = entry.getValue();
if (value > 1) {
System.out.println(key + " occurred " + value + " times");
9578500 occurred 2 times
14850080 occurred 2 times -
Help needed in calculating hash code for a linked list??
I have reffered API documentation for the list interface...There i found the code below for the hashcode() method ...I couldn't get why "31" is used as a multiplicative factor?
int hashCode = 1;
Iterator<E> i = list.iterator();
while (i.hasNext()) {
E obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}I'm a beginner....please help me out..Because it's a prime number, I think. You'll probably want to find an article or decent book on creating optimal hash functions.
-
Get value from the array based on the HashCode
public static void runJoin(int[][] t1,int[][] t2)
PrintWriter out=null;
int rows = 1000;
int cols = 7;
int [][] myTable3 = new int[rows][cols];
int x = 0;
System.out.print("Running HashJoin:Method loads the "+
"smaller table in the memory and applies a hashing function "+
"to common column and stores it in another table. "+
"The larger table is then read from the file. "+
"The same hashing function is applied to Col n of the table and a matching record in the first table is looked up. A match will create a row in Table 3. ");
//Apply hashing function to smaller table and store it in the memory.
Integer[] It2 = new Integer[t2.length];
int [] hashCodest2 = new int[t2.length];
Hashtable ht = new Hashtable();
for(int i =0; i <t2.length;i++){
It2[i] = new Integer(t2[0]);
hashCodest2[i] = It2[i].hashCode();
ht.put(new Integer(hashCodest2[i]),It2[i]);
//Larger table get hashcodes
Integer It1[] = new Integer[t2.length];
int [] hashCodest1 = new int[t2.length];
for(int j =0; j <t1.length;j++){
It1[j] = new Integer(t1[j][4]);
hashCodest1[j] = It1[j].hashCode(); }
//Based on the hashcode get the value from the Table2;
try{
out = new PrintWriter( new FileOutputStream( "c:\\HashJoinTable.txt" ) );
Enumeration e = ht.keys();
while(e.hasMoreElements())
//How do I get the value from the array based on the HashCode? Do I need to do a loop here???
hashCodes1.get(e.nextElement());
}catch(Exception e){}ok I got it......
//Apply hashing function to smaller table and store it in the memory.
Integer[] It2 = new Integer[t2.length];
int [] hashCodest2 = new int[t2.length];
Hashtable ht = new Hashtable();
for(int i =0; i <t2.length;i++){
It2[i] = new Integer(t2[0]);
hashCodest2[i] = It2[i].hashCode();
ht.put(new Integer(hashCodest2[i]),It2[i]);
//Larger table get hashcodes and compare
Integer It1[] = new Integer[t2.length];
int [] hashCodest1 = new int[t2.length];
Hashtable ht2 = new Hashtable();
for(int j =0; j <t1.length;j++){
It1[j] = new Integer(t1[j][4]);
hashCodest1[j] = It1[j].hashCode();
ht2.put(new Integer(hashCodest1[j]),It1[j]);
//Based on the hashcode get the value from the Table2;
try{
out = new PrintWriter( new FileOutputStream( "c:\\HashJoinTable.txt" ) );
Enumeration e = ht.keys();
Integer t3[] = new Integer[t2.length];
while(e.hasMoreElements())
t3[x] = (Integer) ht2.get(e.nextElement());
x++;
}catch(Exception e){} -
Hi,
I have some problems with generating unique hash codes for float arrays.
The following code will result in "true" on my JVM (JRE 1.6):
System.out.println(Arrays.hashCode(new float[]{0,1,2,3,6,9}) == Arrays.hashCode(new float[]{0,1,3,6,8,9}));Does anyone have an idea how to generate a truly unique hashcode for float arrays?
Thanks for your help,
DieterJoachimSauer wrote:
dkleinrath wrote:
JoachimSauer wrote:
But again: you don't usually need a perfect hash. Why do you think you need one?I use static HashMaps to store meta information about specific arrays. I also use a HashSet to search for unique arrays in a big collection of arrays.That's ok. Both HashMap and HashSet can work perfectly with in-perfect hash code (obviously, since perfect hash codes are not possible in many situations).
What they can not handle is .equals() being "wrong" (i.e. inconsistent with hashCode()).
This means that you can't directly use float[] as keys.
You could build a simple wrapper around float[] to be used as keys, 'though.I just tried that and it works like a charm.
Thank you very much for your help. -
hello, i just want to ask, if a certain string converted
into a hash code can be retrieve/turn back to it's
original form?
ex. String n = "alice"; ---> int value = n.hashCode();
can "value" return to "n" as (alice)?
can they provide example code in order to help me solve
my problem? thanks in advance..No.
A tiny bit of logic will tell you this is impossible. There are 2^32 possible hashcode values. There are far more possible strings. Hashcode is not intended to be unique or reversible. -
Problem in not overriding equals and Hashcode
I have a very small question. We know that if we do not override the equals and hascode of Object class, we can not use the object in the Hashed collection. Can anybody provide me a concrete example which indicates the problem if we do not override the equals and hascode.
back to the original question from DebadattaMishra
I have a very small question. We know that if we do
not override the equals and hascode of Object class,
we can not use the object in the Hashed collection.
Can anybody provide me a concrete example which
indicates the problem if we do not override the
equals and hascode.lets extend the example from jverd. Suppose we have a Person and want to store some Score in a HashMapclass Person {
String name;
Person(String name) {
this.name = name;
class Score {
int value;
Score(int value) {
this.value = value;
public class PersonTest {
Map<Person, Score> map = new HashMap<Person, Score>();
void test() {
map.put(new Person("John"), new Score(1));
map.put(new Person("Maria"), new Score(2));
Score score = searchScore("John");
System.out.println("Found: " + score); // Found: null
Score searchScore(String name) {
return map.get(new Person(name));
}if you run test() you will get "Found: null" since the John instance in the HashMap is not the same as used in searchScore. HashMap uses the equals method from Object since we have not overridden it.
If we add an equals methodclass Person {
String name;
Person(String name) {
this.name = name;
public boolean equals(Object obj) {
if(obj instanceof Person) {
Person p = (Person) obj;
return name.equals(p.name);
} else {
return false;
// hashcode not overridden
}we probably will get "Found: null" most if the time. The HashMap uses the hashcode() to create an index for saving the keys, so it mostly will not find the Person.((there is still a very small probability that the correct Person is found))
It will work fine if we add a hashcode like public int hashCode() {
return name.hashCode();
}I hope this example helped. -
hi, i have a CountryTable class which i want to implement as a hash table:
import java.util.*;
class CountryTable {
static int count = 0;
private HashMap table = new HashMap();
public void addEntry(Colour key, Country country) {
table.put(key, country);
count++;
public Country getCountry(Colour key) {
return (Country)table.get(key);
static int getCount() {
return count;
The object which are returned from this table is Country:
class Country {
//static variables
static int count = 0;
//instance variables
private String name;
private Colour base;
//constructor
Country(String name, Colour base) {
this.name = name;
this.base = base;
count++;
//return the number of objects created
static int getCount() {
return count;
//return the name
public String getName() {
return name;
public Colour getColour() {
return base;
The key for the has table is the class Colour, which includes a hashCode() method:
class Colour {
public int rgb;
Colour(int rgb) {
this.rgb = rgb;
public int hashCode() {
return rgb * -1;
I implement these classes in a program as follows:
CountryTable index = new CountryTable();
Colour colour1 = new Colour(-3473408);
Country argentina = new Country("Argentina", colour1);
index.addEntry(colour1, argentina);
Colour colour2 = new Colour(-131072);
Country brazil = new Country("Brazil", colour2);
index.addEntry(colour2, brazil);
Colour col = new Colour(or);
Country coun = index.getCountry(col);
System.out.println(coun.getName());
I have a list of many countries which i set up, with their relevant countires with which they are associated.
The variable 'or' contains an RGB value which has been returned elsewhere in the program. The problem that i have is that when a colour is passed into the getCountry() method, nothing is returned and a "nullPointerException" is thrown, even though a colour with which i set up a country was passed in???
Anyone got any ideas where im going wrong?
Many thanks Cathkeeping the other two files same you change the CountryTable to this
import java.util.*;
class CountryTable {
static int count = 0;
private HashMap table = new HashMap();
public void addEntry(Colour key, Country country) {
table.put(key.rgb+"" ,country.getName());
count++;
public String getCountry(Colour key) {
return (String)table.get(key.rgb+"");
static int getCount() {
return count;
public static void main (String args[]){
CountryTable index = new CountryTable();
Colour colour1 = new Colour(-3473408);
Country argentina = new Country("Argentina",colour1);
index.addEntry(colour1, argentina);
Colour colour2 = new Colour(-131072);
Country brazil = new Country("Brazil",colour2);
index.addEntry(colour2, brazil);
System.out.println(index.table);
String coun = index.getCountry(colour2);
System.out.println(coun);
}and now try -
How to implement hashCode() function
Hello everybody
I need to overrided hashCode method in my Object. This contains 4 attributes of type Long. I need to implement compatible hash code for my equals function.
public class MyObject {
Long attr1;
Long attr2;
Long attr3;
Long attr4;
public boolean equals(Object obj) {
if (this == obj)
return true;
if (this == null || this.getClass() != obj.getClass())
return false;
TSCObject object = (TSCObject) obj;
return (this.attr1 != null && this.attr1.equals(object) &&
this.attr2 != null &&
this.attr2.equals(object) &&
this.attr3 != null && this.attr3.equals(object) &&
this.attr4 != null &&
this.attr4.equals(object));
public int hachCode() {
return 0;//??????????????
Can somebody help me. I've heard something about HashCodeBuilder
ThankIt is hashCode(), not hachCode().
You can consider to return the sum of the attr1.hashCode() + attr2.hashCode() + etc. You should try to "guarantee" as much as possible that the hashCode() returns an unique identifier of the MyObject in such a fast way so that it will improve performance of hashmaps/sets/tables which are used to store those objects. If you put a new MyObject in such a hashmap/set/table then it will check based on the hashcode if the object doesn't already exist. If it does, then it will invoke the equals() to check if they are certainly equal (which is generally more expensive).
Also see http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode() -
How hashtable handle hash collision?
From Class Hashtable javadoc
"in the case of a "hash collision", a single bucket stores multiple entries,
which must be searched sequentially."
if a single bucket stores mulitple entries of String object, how
could mulitple entries be retreived like this situation?
String s = hasht.get(key)
I tried a small test myself using two identical hascode "BB" and "Aa" and they get stored in 2 different bucket in hashtable but not mulitple entries as stated at the
javadoc. Thank you.debugger indicatedumm, the hashes are the same so ur right there, you must have read the debugger wrong though
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { // right here it is same entry but its like a list inside the bucket
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
// rehashing stuff removed for post...
// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++; -
How to override hashcode() in String
I need to override the hashcode() method in java.lang.String with a cyclic shift hash code. how do I do this? String is final so I cannot extend it. I've looked at all the postings regarding the logic of why hashcode() must be overwritten with equals() etc, but I need some thoughts on how to actually override the method.
public class MyString { // you are right, you can't extends java.lang.String
private String str; // but you can wrap it
public MyString(String s) {
this.str = s;
public String get() {
return this.str;
// ... implement all or most String methods again ...
// ... then ...
public int hashcode() {
return whatEverYouWant; // but make sure it is consistent with equals
public boolean equals(Object obj) {
return (MyString)obj.get().equals(this.get());
}--lichu -
What is the hash code of an object? What does hash code mean?
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Obje
ct.html#hashCode()also http://en.wikipedia.org/wiki/Hash_code
what the hashcode isn't, though, is an identifier for an object, unique or otherwise. don't make that mistake!
"Database Systems" by Connolly-Begg has a good section on hash codes and their uses, if memory serves me well
Maybe you are looking for
-
"Maximum package size for data packages was exceded".
Hi, We are getting the below error. "Maximum package size for data packages was exceded". In our scenario we are loading the data product key wise (which is a semantic key as well) to the DSO thro' a start routine. The logic in the start routine is s
-
Hey - I somehow have edited most of a very complicated video with the wrong sequence settings. For some reason, it's set to both a 4:3 aspect ratio and a much smaller image size, but I didn't notice because it retained the aspect ratio of the video f
-
How to I set a song to a contact
I have copied my CDs to my Iphone and I want to attach certain songs to individule contacts. Can you please help me ? Janey
-
I can't get angry birds space danger zone to download. I have a receipt but it won't download. I bought angry birds space and music just fine but this game won't download. Also says can not connect to iTunes store.
-
Which two are attributes of /SQL*Plus? (Choose two)
A. /SQL*Plus commands cannot be abbreviated. B. /SQL*Plus commands are accesses from a browser. C. /SQL*Plus commands are used to manipulate data in tables. D. /SQL*Plus commands manipulate table definitions in the database. E. /SQL*Plus is the Oracl