7
String s1 = "String1";      
System.out.println(s1.hashCode()); // return an integer i1 


Field field = String.class.getDeclaredField("value");  
field.setAccessible(true);  
char[] value = (char[])field.get(s1);  
value[0] = 'J';  
value[1] = 'a';  
value[2] = 'v';  
value[3] = 'a';  
value[4] = '1'; 
System.out.println(s1.hashCode()); // return same value of integer i1 

Here even after I changed the characters with the help of reflection, same hash code value is mainatained.

Is there anything I need to know here?

6
  • 5
    If it's the same value, then it is cached. What other proof do you need? Go to the source code. Commented Jan 8, 2014 at 16:02
  • Cool. Another question would be When it's re-evaluated ? Commented Jan 8, 2014 at 16:03
  • 1
    Using Reflection breaks the API of String, which causes this unexpected behaviour Commented Jan 8, 2014 at 16:03
  • @kocko: never, since String is immutable (unless the computed hashCode is 0, which also means "not computed yet") Commented Jan 8, 2014 at 16:05
  • @JBNizet, thanks. Really cool question for interview. :) Commented Jan 8, 2014 at 16:06

1 Answer 1

14

A String is meant to be immutable. As such, there is no point having to recalculate the hashcode. It is cached internally in a field called hash of type int.

String#hashCode() is implemented as (Oracle JDK7)

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

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

where hash initially has a value of 0. It will only be calculated the first time the method is called.

As stated in the comments, using reflection breaks the immutability of the object.

Sign up to request clarification or add additional context in comments.

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.