Difference between @ and # in Java toString output?

What is the difference between the @ and # characters denoting the output of toString? I have a Java object that does not override toString. When viewing a log file, I see on some lines

com.foo.model.orders.Order@10eb9e65 

while on the other line (this is issued from sleep mode), I see

 com.foo.model.orders.Order#51a4cfa1e4b047bf2ab9b796 

Is there a way to translate these two numbers to determine if they are the same instance?

+4
source share
3 answers

No.

Both of these numbers are simply arbitrary internal parts from two different systems. None of them guarantees what they are, or how they are developed.

If you came up with some kind of translation, it would be very fragile and prone to breaking without warning under any changes in circumstances (different versions of library / JVM patches working with a bunch of different sizes, etc.)., And I suspect that, there is probably no connection between them. I know that the first number is generated by the JVM, usually based on the actual location of the memory that the object occupies. The second will be a kind of hash generated by Hibernate - which does not have access to the same information as the JVM, and therefore is unlikely to use the same input.

+4
source

The hash format, as you expected, comes from Hibernate. To answer your question from the comments on your question, Hibernate in several places registers the name of the object / class, hash sign, and then the primary key of the entity. So com.foo.model.orders.Order#51a4cfa1e4b047bf2ab9b796 is an order with primary key 51a4cfa1e4b047bf2ab9b796 .

As others have stated, if you want to check if two objects are the same instance, == will do this more simply and reliably than comparing their string representations.

+1
source

If you are trying to determine if references to 2 objects refer to the same instance, use Object.equals

The equals method for the Object class implements the most discriminatory possible equivalence relation of objects; that is, for any nonempty reference values ​​x and y, this method returns true if and only if x and y refer to the same object (x == y is true).

If you just want your log file to display enough information to determine if they are the same instance, override toString to provide enough information or modify your log message.

---- EDIT ----

To clarify @Jimothy's comment, use order1 == order2 instead of .equals

0
source

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


All Articles