Monday, 30 May 2016

java - Object is same but the output is different ? please help









public class AboutStrings{
public static void main(String args[]){
String s1="hello";
String s2="hel";
String s3="lo";
String s4=s2+s3;


//to know the hash codes of s1,s4.

System.out.println(s1.hashCode());
System.out.println(s4.hashCode());

// these two s1 and s4 are having same hashcodes.

if(s1==s4){
System.out.println("s1 and s4 are same.");

}else
System.out.println("s1 and s4 are not same.");
}
}


In the above example even though s1 and s4 are refering to
same object(having same hash codes),



it is printing s1 and s4 are not same.




Can anybody explain in detail why it is behaving like this?


Answer



Just because two objects have the same hash code does not mean they are the same object (you are checking with == the object identity!).



You may want to call



s1.equals(s4)



instead - but even then, both could have the same hash code without being equal either: two objects that are equal must have the same hash code (to work properly in Collections etc), but not vice versa.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...