File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string == and hashcode

 
John Summers
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
The code below prints "not == -891985903 -891985903".
Can anyone explain why:
a) a and b are not the same object. is it perhaps because the trim occurs at run time?
b) howcome a does not == b? I thought == worked by comparing hashCodes, and the hashcodes are the same.
thanks
john

public static void main(String[] args)
{
String a = " string ".trim();
String b = "string";

if (a == b)
{
System.out.println ("==");
}
else
{
System.out.println ("not == " +
a.hashCode() + " " + b.hashCode());
}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

is it perhaps because the trim occurs at run time?

Yes, a and b are not the same object. The result of calling " string".trim() is computed at runtime and a new, distinct String "string" is created, unrelated to the pre-existing String literal with the same value.

I thought == worked by comparing hashCodes,

Nope, not at all. "==" works by comparing physical chunks of memory, always. You can have an arbitrarily large number of Strings, all of which contain the same characters in the same order, but which are physically distinct objects. They'll all have the same hashCode(), and they'll all be not equal according to "==".
The equals() method, on the other hand, is supposed to return true for equivalent objects; so given two distinct String objects s1 and s2 both containing the characters "string", s1.equals(s2) would be true, while s1 == s2 would be false.
It very rarely makes any sense to use == to compare strings. Use equals() instead.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should note that objects with the same hashcode are not guaranteed to be equal. A hashcode method that returns a constant 0 for all objects is a correct (although inefficient) implementation according to the specs.
Why is hashcode not the same as equals? hashCode() always returns an int. For any int I can create an equaivalent string. For example:
int a = 1;
String as = "1";
int b = 132;
String bs = "132";
So clearly I can create a different String for every possible int. But I can also create Strings that don't have an int equaivalent:
String as1 = "1 + some other stuff";
This means that ints can not represent all the possible Strings. So there must be some cases where two Strings will have equal hash codes even when the Strings themselves are not equal.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic