0

Why is the hashcode of stringObject is the string I provided?

String s = new String(); // here the hascode is 0. 

But when i get the hashcode of some object i created.

testClass o = new testClass(); // the hashcode is some random number.

My question is what is the difference between the two? My understanding is hashCode() is from Object class which is the mother of all class.

6
  • 2
    Any class can redefine hashcode. Commented Mar 30, 2012 at 14:52
  • @UmNyobe: But the return value can't be changed, which is why the question doesn't make sense. Commented Mar 30, 2012 at 14:53
  • the hashcode is an int, so I am not sure where you see it as being "hello"... Commented Mar 30, 2012 at 14:53
  • I was answering to hashCode() is from Object class which is the mother of all class. Commented Mar 30, 2012 at 14:54
  • And no need to instantiate String here, simply write String s = "hello"; Commented Mar 30, 2012 at 14:56

7 Answers 7

7

Why is the hashcode of stringObject is the string I provided? ex. String s = new String("hello"); // here the hascode is hello.

That is Not true

hashCode() is an int number

You seems confusing hashcode() with toString()

if you want to check the hashcode()

String str = "hello";
System.out.println(str.hashcode());//will print some int number
System.out.println(str);//will invoke toString() which will return `hello`
Sign up to request clarification or add additional context in comments.

5 Comments

I already answered, please read You seems confusing hashcode() with toString()
No. please look in my question I just edited it i remove "hello" but why hashCode() is not some random number?
You are right that Object declares hashcode() but the implementation differs in String class, String class overrides hashcode method while your class doesn't so your class (if not overriding) hashcode will invoke object's default implementation that is the reason the numbers are different, hope this helps
OK now that helps thanks, sorry for not checking before posting my question.
@JigarJoshi: The answer does not answer the edited question, but the comment does. Please edit the answer to contain this information so it will be useful for future readers as well.
0

I think you're confusing hashCode() with toString().

The default toString() implementation of every object is indeed <classname>@<some number> and the number happens to be the hash code of the object in hex, but that can (and should) be overridden by classes that can provide a more meaningful string representation. And for a string, the obvious string representation is itself.

Comments

0

String s = new String("hello"); hash code of this will never be Hello, because hashCode() methods return type is int not a string

Comments

0

String is a class provided in the Java library. Thus, the hashCode() method has been overridden by creator of this class to reflect it. Please not that the hashcode is an int value.

When you create a class, you want to override both hashCode() and equals() method, in order to be able to compare your objects, and do other cool stuff (putting them in a HashMap, for example).

You need to be careful on how you would implement hashCode() as you want to respect the general contract, that states that if 2 objects are equal according to equals() method, they have the same hashCode(), while the opposite doesn't have to be necessarily true (but it's recommended).

You can find a more deep explaination here - http://www.javaworld.com/community/node/1006

Comments

0

The method hashCode() always returns an integer which is the hash value of an object. An nativ implementation is available in class Object. If you want to create your own hash of a type, you have to overwrite hashCode().

toString() will return the string representation of an object and hashCode() (as descripted above) the hash value of an object.

The class String overwrites hashCode(). This is how it's done by String:

public int hashCode() {
    int h = hash;
    int len = count;
    if (h == 0 && len > 0) {
        int off = offset;
        char val[] = value;

        for (int i = 0; i < len; i++) {
            h = 31*h + val[off++];
        }
        hash = h;
    }
    return h;
}

Comments

0

There are some issues here:

  1. as other has already said - hashCode() returns an integer, and you might be confusing with toString()
  2. Which is more important IMO: Object has both hashCode() and toString() methods. However, any subclass of Object can override this method. When the method will be called - the dynamic type's method will be invoked, so for String, String.hashCode() will be invoked and not Object.hashCode() [same idea for toString()]. This is called dynamic dispatch.

for example:

public static class A { 
    public void foo() {
        System.out.println("A");
    }
}
public static class B extends A{ 
    @Override
    public void foo() {
        System.out.println("B");
    }
}
public static void main(String[] args) throws Exception  {
    A a = new B();
    a.foo();
}

In the above code snap, B.foo() will be invoked, and B will be printed, since B overrides foo(), and the dynamic type of a is B, so B.foo() is invoked.

In your case: Since String overrides hashCode(), then String.hashCode() is invoked, while for testClass - it doesn't override hashCode(), so the original Object.hashCode() is invoked.

Comments

0

I think you are getting confused due to hashcode of empty string which is 0. Hashcode is always an integer which is computed by hashcode function available for that class. Now, hashcode of any custom class is provided by the Object class(default parent) hashcode method which returns the memory address of that object in int form.(if not overridden by custom class)

Now you can think of String as a custom class but created by some other user who override this hashcode function for strings in String class which now computes it like: S[0]*31^(n-1)+S[1]*31^(n-2)+...+s[n] , 0 for empty string. All the calculations included for evaluating above expression are integer calculation of java. You can refer to https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#hashCode()

The String class of java overrides hascode function so that when you call hashcode on two different String objects with same string in them will result into same hashcode; which is usually important while useing hashing techniques in hashed data-structures like hashmaps. So this overridden function provides same hashcode for both String s1=new String("hello") and String s2=new String("hello") ; whereas in memory they have been stored as different Strings. Now if you want your custom class to have same hashcode on basis of some property of that class you can override the hashcode in your class as String does on tha basis of actual string stored in it.

So in your case 1; you get 0 and in cade 2 you get some memory location in int form as explained above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.