An interesting issue came up recently. We came across some code that is using hashCode() as a salt source for MD5 encryption but this raises the question: will hashCode() return ... |
The hashCode value of a Java String is computed as (String.hashCode()):
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
Are there any circumstances (say JVM version, vendor, etc.) under which the following ... |
I'd like to compare some large objects representing trees and cache something to avoid comparing each time the new object with one already existing...
The question is what would be the best ... |
Typically the default implementation of Object.hashCode() is some function of the allocated address of the object in memory (though this is not mandated by the JLS). Given that the VM shunts ... |
The default behavior of Object.hashCode() is to return essentially the "address" of the object so that a.hashCode() == b.hashCode() if and only if a == b. How can I get ... |
In java, if I want generate a id for a given object, the easyest way I know is to use apache commons:
public class Person {
String name;
...
|
Is it possible for two instances of Object to have the same hashcode ?
In theory an object's hashcode is derived from its memory address, so all hashcodes should be unique, ... |
|
In our application we generate hashcode from a java object and store it in the database at some level.
Now my questions is if somebody generates a number by hand, is there ... |
Eclipse 3.5 has a very nice feature to generate Java hashCode() functions. It would generate for example (slightly shortened:)
class HashTest {
int i;
int j; ...
|
I've recently encountered an odd situation when computing the hash Code of tuples of doubles in java. Suppose that you have the two tuples (1.0,1.0) and (Double.POSITIVE_INFINITY,Double.POSITIVE_INFINITY). Using the idiom stated ... |
I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet:
public class Main{
...
|
I have list of a an object which is termed as rule in our case, this object itself is a list of field for which I have to do hashcode comparison ... |
The signature of the hashCode() method is
public int hashCode(){
return x;
}
in this case x must be an int(primitive) but plz can anyone explain it to me that the ... |
when i run this from the repl:
(def md (MessageDigest/getInstance "SHA-1"))
(. md update (into-array [(byte 1) (byte 2) (byte 3)]))
I get:
No matching method found: update for ...
|
I have this simple class
public class Position{
int x;
int y;
Position(int x,int y){...}
public int hashCode(){
Integer ix = ...
|
In java obj.hashcode() return somevalue.My question is what is the use of this hash code in programming?
|
Hey so I'm sorry if this is really obvious but I was just wondering why is that primes are used in a class's hashCode() method? For example, when using Eclipse to ... |
Now I see how to implement a method hashCode() for the Boolean object:
public int hashCode() {
return value ? 1231 : 1237;
}
And I wonder why it returns a values 1231 or ... |
Possible Duplicate:
How do hashCode() and identityHashCode() work at the back end?
what is the difference between hashCode() and identityHashCode()?
|
I was trying to find some approximization to address on heap , and you guys gave me the fucntion System.IdentityHashCode(Object).
The problem is - this function doesnt fit for primitive types. I'll ... |
I have this program:
import java.util.*;
public class test {
private String s;
public test(String s) { this.s = s; }
public static void ...
|
In my implementation, I have a class A which overrides equals(Object) and hashCode(). But I have a small doubt that is, while adding the instance of A to HashSet/HashMap the value ... |
Is there any way that I can use a hashcode of a string in java, and recreate that string?
e.g. something like this:
String myNewstring = StringUtils.createFromHashCode("Hello World".hashCode());
if (!myNewstring.equals("Hello World"))
...
|
Can someone please explain why hashCode is called in the example below?
import java.util.List;
public class JSSTest extends Object{
public static void main(String args[]){
...
|
What is the best way to implement a cache for Sets? Particularly, what makes the best key for the cache?
In a static factory method, I want to include a caching mechanism, ... |
Only interesting, why method hashCode() in java.lang.String is not static?
And in case of null return e.g. -1 ?
Because frequently need do somethihg like:
String s;
.............
if (s==null) {
return 0;}
else {
...
|
Is Java String.hashcode() completely independent of Locale? In other words, if someone fiddles with the default Locale, are we 100% sure this is not going to impact ... |
I have defined a subinterface of java.util.Collection that effectively is a multiset (aka bag). It may not contain null elements, although that's not crucial to my question. The equals contract defined ... |
I have an interface, EventHandler (OSGi EventAdmin), with a single method handleEvent(Event).
I have the following Javascript code:
importPackage(org.osgi.service.event)
obj =
{
handleEvent: function(event)
{
...
|
A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable. Imagine the following simple example: On the table in front of you you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once ... |
Hi! Have you people ever think that how reliable java's hashCode actually is if hashCode is generated from String by VM's default implementation.. I have think that if i have a map, where i put host names, is it possible that two different host name gives same hashCodes?!? i think Let's think that we are using unicode charset (not for host's ... |
I am experiencing a wierd problem. There is a base class Symbol which extends Hashcode and equals method. I made sure they are implemented correctly. There is another Class TokenType which extends the Symbol Class. The problem that I am seeing is as follows: I am running a test program which uses the package which has both the above mentioned classes. ... |
|
Hopefully someone can help me with this issue: I have a structure (suffix tree) that is built using hashmaps. In these hashmaps I store objects. Each object has a string field. If anyone is familiar with how a suffix tree works this will make sense. Basically I store a sequence of objects on the tree. When I add the suffix part ... |
Hi, For the Java String's hashcode() implementation: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] (jdk source code): int h = 0; int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } I am curious to find out the reason for using base 31. ... |
|
Hi all, I have a doubt regarding run time calculation of hashcode. For example we have specific hashCode method for objects of class A . In some other class, say B, we have collection of objects of class A.Now in one method of class B I try to retrieve hash values of objects of class A. My question is do I ... |
Can somebody tell me what is use of hascode? Till this day I was thinking that hascode is used to identify uniqueness of the object , but actually it is not. If I create two string objects String a = haha; String b = new String(haha): It creates two different objects but the hascode is same for two different objects. Now ... |
I don't think I've ever written a program where I need to call hashCode() directly. Many Collections use hashCode() to figure out how to retrieve and store objects. In particular, many implementations of the Map interface use it. If you are interested, I strongly suggest you learn more about data structures. Hash codes are a more general concept that is used ... |
What you quoted was a statement of intent, not a statement of fact. Or to paraphrase myself, they are hinting that you should always override hashCode when you override equals. Otherwise you could define an equals contract that returns different hashCode values and things would just start breaking and you may never know why... |
41. Hashcode coderanch.comHi, Can a hashcode overridden from Object, can return other than int. Because i can an object which has teh value that sis greater then the int can hold.No way of reducing the value of my object, because i have to check against the same object.I even tried dividing the value by some int to make it smaller value so taht ... |
|
Is that 'they' as in "You know what they say about Michael"? There is a good introduction on the why and how at the Java glossary. The short answer is that it is handy having a fast way to 'guess' whether two objects are the same, then compare them only when you have to. Hashcodes should be implemented to give a ... |
44. hashcode coderanch.comI have read that hashCode() function of the object class returns the memory address of that object and it is recommended to implement our own hashCode in our classes for better hashing. Since every object has a unique address, the default implementation seem to provide a good hashing scheme. I am wondering why the default implementation is not the best. |
Writing equals() and hashCode() implementations for a concrete or abstract class is pretty easy, but what do you do when an interface gets involved? As an example, let's say I have an Address interface and every Address has five attributes: street address, city, region, postal code and country. public interface Address { public String getStreetAddress(); public String getCity(); public Region getRegion(); ... |
public class HashCode { public static int hashCode(String s) { int hash = 0; for (int i = 0; i < s.length(); i++) hash = (31 * hash) + s.charAt(i); return hash; } public static void main(String args[]) { String s = args[0]; System.out.println( System.identityHashCode(new HashCode())); System.out.println( new HashCode()); System.out.println( (new HashCode()).hashCode()); } } hi, here i am displaying a hashcode ... |
Joshua Bloch, in Item 8 of his book Effective Java Programming Language Guide, suggests an algorithm for calculating a hashcode. For a class with a single long field for a key, the resulting code would look like this: int c1 = 37; int c2 = 17; int result = (int)(f ^ (f>>>32)); int hash = c1 * result + c2; where ... |
I'm not sure what's meant, but let's think about hashcode on different objects. On a mutable object we'd want to compute hashcode from the current state. The state could change, so if we stored hashcode in a variable for later use we'd have to recompute it any time something changed. That's wasteful because we might never use hashcode again. On an ... |
|
|
|
Hi, Read the code, public static void main(String[] args) { String siva=new String("sivakumar"); String siva2=new String("sivakumar"); String siva1="sivakumar"; String siva3="sivakumar"; System.out.println(siva.hashCode()); System.out.println(siva1.hashCode()); System.out.println(siva == siva1); System.out.println(siva == siva2); System.out.println(siva1 == siva3); } The output is: 1138315475 1138315475 false false true My doubt is, == method check the hashcode and return true if two hashcode has the same value but the above ... |
No. It's hashCode not hashcode. Go and look through the API for java.lang.Object and you find this method is designed to return the same value for pairs of objects where equals() returns true. It is not designed for high-security applications. Don't know a lot about that, but I think you need to go through the API for SHA1 classes. |
Originally posted by Tanzeem Akhtar: Hi, well i am unable to understand that why it is mandatory to have same hash-code, if two objects are same? Thanks in advance. Short answer... It mandatory because that is the contract. Longer answer... The way the hash set and map works is to only check for equality in the bucket that it ... |
|
class Team { private static final int HASH_PRIME = 1000003; private String name; private int wins; private int losses; public Team(String name) { this.name = name; } public Team(String name, int wins, int losses) { this.name = name; this.wins = wins; this.losses = losses; } /** * this overrides equals() in java.lang.Object */ public boolean equals(Object obj) { /** * return ... |
Assuming that I have the following two classes defined: public class Widget { public Widget(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } private final String id; private final String name; } public class Gadget extends Widget { public Gadget(String id, String name) { ... |
58. hashcode coderanch.comHello Everyone. How are you WE HAVE A LITTLE PROBLEM IN WRAPPER CLASSES. public class wr { public static void main(String s[]) { String str=new String("hello"); int obj=str.hashCode(); System.out.println("Hash code OF STRING is:"+obj);//1.HASH CODE IS 99162322 Double b2=Double.valueOf("3.0"); Double b3=new Double("4.0"); Integer b4=new Integer("77"); int obj2=b2.hashCode(); int obj3=b3.hashCode(); int obj4=b4.hashCode(); System.out.println(obj2);//2.HASH CODE IS 1074.... System.out.println(obj3);//3.HASH CODE IS 10745..... System.out.println(obj4);//4.HASH CODE IS ... |
Yeah, I looked through the API and also read about hashcodes in many different resources, but still never fully understood how they were calculated. I know they're used for the equals() method, but how exactly are they calculated? And are they small ints, like 1 or 2, or big like 214563 or something? And do we ever need to know the ... |
I encountered the following code and explanation in Core Java2 ( page 97 ) String s ="Ok"; StringBuffer sb= new stringBuffr(s); System.out.println(s.hashCode() + " " + sb.hashCode() ); String t="Ok"; StringBuffer t= new stringBuffr(t); System.out.println(t.hashCode() + " " + tb.hashCode() ); The hashcode for both strings is same and the hashcode for both the string buffers will be different from each ... |
Please check the Java docs. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an ... |
A hashcode is usually used as an efficient way of searching for stored objects. Say you have a list of 1000 names, it would take a reasonable amount of time to search for the name "Jeremy Thornton" in the list. If however you stored the names according to their hashed value (which is what the HashX type containers do) you just ... |
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ... |
I keep getting a NullPointerException, do I need an iterator or am I writing the hashCode() portion wrong? public class Person { private String name ; private int number ; public Student( String name , int number ) { name = name ; number = number ; } public String getName() { return name ; } public int getNumber() { return ... |
Hi Syamsul, An objects hash code determines what "bucket" it goes in, in a hashtable (or any Collection that is backed by a hashtable). That's why if you override the equals() method in a class then you must also override the hashCode() such that if two objects are equal then they are required to have the same hashCode. Two unequal objects ... |
|
67. hashCode coderanch.comThere is no way to tell from a hash code what type an object is or what its value(s) is/are. Well, there is a way to reconstruct a String value from its hashcode, but it's very ugly and not reliable. The only purpose of doing it may be as an exercise to see how the hashCode() works in a particular JDK ... |
It's hard to know in these discussions who you're talking to ... I apologize ahead of time if this is talking down to anyone who doesn't deserve it ... Those were pretty nice articles. I liked a couple words they used. One was "dictionary", common in Smalltalk. It's a nice concept - given a word, return the definition. The other article ... |
Hi, I try to use the formula below to implement the hashCode() of my class, say ClassA. There are 6 String fields to be compared in the equals() and hence my hashCode() will include these 6 fields. On using this formula, the calculated hash code is very large, sometimes it is negative, say -1342574843. I guess it is because the value ... |
I have the following output: JOHN DOE : Java Calculated hash=4 for JOHN DOE students[hash]: JOHN DOE : Java students hashCode value = 21990827 Could someone explain why I got the hashCode value = 21990827 and NOT 4? (4 is what I was expecting? students [hash] = studentDetails[lp]; System.out.println ("students[hash] : "+students[hash] + " students hashCode value = "+ students[hash].hashCode( ) ... |
the hashcode is NOT the address in memory of an object instance. In fact, that would yield a hashcode which is by definition incorrect as it doesn't confirm to the hashcode definition which states explicitly that two identical objects MUST have the same hashcode. As no two objects (whether identical or not) can exist in the same place in memory at ... |
HI i think the problem i have is with my hashCode method can anybody help me out with this? basically i have three files Student, Storage and one for the main method. It is suppose to accept user input for name and course via JOptionPane until the maximum size is met then display the list of names and courses as the ... |
The method is named "hashCode()" -- with a capital "C". Case is significant in Java. You're also going to have problems with this line: int obj4 = x.hashcode(); because "x" is an int, because you can't call methods on ints or other primitive types. One more thing, while you're listening: There's essentially never any reason to write String str = new ... |
A hash code is a number, period. It's whatever you say it is. Hash code functions are either good or bad. If you take input data and generate a number from that data using an algorithm of your choosing, you have a hash code. Here is a hash function for string data that returns a hash code: int hash(String data) { ... |
I am not clear about overridding rules of hashCode () with equals() 1.Is is constraint if we override one method,we have to override another. or for performance purpose.AS i tried ,it doest give any error. 2.we get Questions to select best overriding method.How do we decide that. Is it like ,hashCode() should be minimally dependant on objects variables. thnx |
To follow up on that, two objects that are equals must also have the same hashcode. As Ernest pointed out, the hash codes can be used in HashMaps and HashSets. What happens is that if you tell a HashSet to look for an object, it hashes the object you tell it to look for and then finds if it has an ... |
|
Hi Ranchers, Does the hashcode() of the object return the same number for different executions? I am calculating the hashcode of the object to see if the object is changed. this works fine as long as i dont restart my server(App Server). But, once i restart the server the hashcode of the object changes even though the original object doesn't change. ... |
|
Thanks to both of you, just one last doubt ; i found it weird the hasCode method gets called even if i print the HashCode object . I am pasting the code along with output import java.util.HashMap; import java.util.HashSet; import java.util.Set; class HelloEx { String str = "HelloEx" ; HelloEx(String s){ str = s ; } public int hashCode() { System.out.println("Inside ... |
Not necessarily. It all depends on the implementation of the hashCode() method. Object returns an identity hash code, so if that implementation is used the answer is (most likely) yes. However, I could override the hashCode() method to return a constant, e.g. 42. Now all objects of my class will have the same hash code. Granted, it's an unpracticle example, but ... |
I'm a little hazy as to the need of an objects hashcode. It is my understanding that hashcode is a generated number of sorts that identifies a particular Class. So if you were to ever compare an instance of Class A with another Instance of Class A their hash codes would be the same. Their equals() may or may not be ... |
|
84. hashcode coderanch.com |
|
In khalid Mughal page 511, hashcode() method is given in detail. I have nor understood certain questions: What will happen if unequal objects will hash to same bucket ? (page 513) I know that equal objects should hash to same bucket in the hash table, it enables yielding correct answer on searching that object. But where is the prob if unequal ... |
I have read the Java tutorial and as much as I can google on the above subject but I am struggling to understand the basic concept. Unfortunately my brain will not absorb any more information until the block is removed. The problem is this: "you will calculate the same hashCode, and will be able to look up numerically with it. Of ... |
The number 31 was chosen because it is a prime number. (They could have chosen any other prime number). To understand why a prime number was chosen, you have to know how hash-based collections such as HashSet and HashMap work. Hash-based collections store elements in so-called buckets. A hash-based collection has a fixed number of buckets. When you put an object ... |
|
import java.util.*; class MapEQ { public static void main(String[] args) { Map, String> m = new ToDos("Monday"); ToDos t1 = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new ToDos("Tuesday"); m.put(t1, "doLaundry"); System.out.println(m.size()); }} class ToDos { String day; ToDos(String d) { day = d ;} public boolean equals(Object o) { return ((ToDos)o.day == this.day } // public int ... |
Thanks for helping me understand, As I understand when I call hashcode() method for the first time, it returns the memory address but subsequently calling hashcode() method is not sure to return the memory address because the object may be garbage collected and Object's hashcode() method returns identity hashcode. My doubt is: If I have A a = new A(); Lets ... |
|
93. hashcode coderanch.comAfter reading some articles about Hashcode, here is my conclusion. 1. hashcode is for loop-up speed. so it mostly used with hashset... 2. hashcode itself doesn't need to be unique, but with equals(), it has to be unique. 3. how hashcode works ? for a container, like hashset, it will calculate hashcode, then put it into an array. if no collision, ... |
|
95. HashCode coderanch.comWhen an object is created in a java class, does it carry system generated hashcode ? If so, then every object will carry unique hashcode, right ? public class TestHashcode { A a1 = new A(); A a2 = new A(); int a1Hashcode = a1.hashCode(); int a2Hashcode = a2.hashCode(); } In this example, a1 and a2 will have unique hashodes for ... |
The == operator always compares objects for identity. Meaning it will only return true if two references point to the exact same object. Byte, Short, Character and Integer put their instances in their own respective pools, in the same way String does; with the exception that String does it with every literal, while the former classes only do so for byte-sized ... |
I have the following code. Lines 61 through 67 are supposed to be removing the duplicates from the list of titles coming from the file. However when I run this in NetBeans the duplicates appear. What do I need to do to have the duplicates removed? Thank you for your help. package jukebox6; import java.util.*; import java.io.*; public class Jukebox6 { ... |
|
Hi guys, I just have a question about a method that my teacher wrote to generate hash codes for Strings. I guess there are many different ways to get hash codes. The code is the following: public int hashCode() { int x=0; for (int i =0; i < str.length(); i++) { x=(((int) str.charAt(i)) + 256*x)% modulus; // modulus here is the ... |
It would help if you print out more details -- such as "name" or other parts of the instance, in addition to the hash code. We don't know anything about the instances that you are referring to. And BTW, it is valid for two unequal instances to have the same hash code -- so there may be nothing wrong. Henry |