How to check referential equality in an object that implements content equality?

... in other words: suppose I have 2 lines declared like this:

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

these two lines 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 content level equality. However, I need to access the reference level of equality (for example, implemented in Object) to distinguish the object from the shape of the object. How can i do this?

I tried this:

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

to try to call the equals () method of the String object, but it does not work.

Any tips?

+4
source share
5 answers

String In java, String Literal Pool , which means: "When you try to build a string, first search the String class in Literal Pool for the traditional same string, if it exists, return it, and if it doesn’t, create it", so you cannot To check the equals compare refernce method of the String instance, you should use the == operator as follows:

 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:

 equals() returns true. 

see the following link for more information:

+2
source

If you want to verify that the link just does:

 one == two 

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

+2
source
 if (one == two) System.out.println("one and two are the same object"); 
+1
source

Use a simple comparison == . However, to avoid String interning, you must create your strings using char arrays, for example: String me = new String(new char[] { 'm', 'e' }); , instead of using String "me" literals, such as String me = new String("me"); .

+1
source

The only thing you need is the equality operator == ==.

0
source

Source: https://habr.com/ru/post/1398465/


All Articles