Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check reference equality in an object which implements content equality?

...in other words: let's suppose I have 2 Strings declared as so:

String one = new String("yay!");
String two = new String("yay!");

these two Strings are two different objects, but if I run

if(one.equals(two))
   System.out.println("equals() returns true.");

I get "equals() returns true". This is because the String class overrides the equals() method to implement a content level equality. However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two. How can I do that?

I tried this:

one.getClass().getSuperclass().equals();

to try to invoke the Object equals() method of the String one but it didn't work.

Any advice?

like image 322
MaVVamaldo Avatar asked Feb 26 '12 13:02

MaVVamaldo


2 Answers

If you want to check reference just perform:

one == two

But be careful with strings. There is a thing called String constant pool so they may refer to the same object.

like image 171
tom Avatar answered Sep 25 '22 21:09

tom


String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:

String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
   System.out.println("equals() returns true.");
if(one == two)
   System.out.println(" == operator returns true.");

result is :

equals() returns true.

see following link for more information:

  1. http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
  2. Java String.equals versus ==
like image 38
Sam Avatar answered Sep 25 '22 21:09

Sam