0

I have two objects from database (in database it is same object), but they have different hashes:

GroupType groupType  = groupTypeDao.findById(3);
GroupType groupType1 = groupTypeDao.findById(3);
System.out.println(groupType);
System.out.println(groupType1);

I get this output:

GroupType@6040
GroupType@6041

Why is that? Technology stack: Spring, JavaFX, Hibernate.

I have another project with Spring and Hibernate. Configuration files are identical in the two projects. Hibernate version is identical also. But in another project this produce same hashcodes.

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
Virkom
  • 373
  • 4
  • 22
  • Those are not the `HashCodes`... – brso05 Oct 12 '16 at 13:16
  • Do: `groupType.hashCode()` and `groupType1.hashCode()` and see what you get... – brso05 Oct 12 '16 at 13:17
  • 1
    Those are the `toString` values which default to `hashCode()`... Which you probably haven't implemented. – M. Deinum Oct 12 '16 at 13:18
  • What you see is string-decorated _identity hash code_. See `java.lang.Object#toString()` for the source code of what you get. – Lyubomyr Shaydariv Oct 12 '16 at 13:19
  • I try to programmatically select row in TableView. I save object to database, load frame with TableView, get list of all objects from database and put it to TableView like this: `tableView.setItems(list);` Then I try to select this object and focus it. `tableView.getSelectionModel().select(object)`. But object not found in list because it has another hashcode. Row not selected, not highlighted. – Virkom Oct 12 '16 at 13:25
  • Your `object` instances just must have `equals()` and `hashCode()` overridden right. See here: http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java – Lyubomyr Shaydariv Oct 12 '16 at 13:29
  • brso05, I did it. `System.out.println(groupType.hashCode());` and `System.out.println(groupType1.hashCode());` It gives this output: `2134186094`, `1311827441` – Virkom Oct 12 '16 at 13:31

2 Answers2

4

What you've printed are object references. They are indeed different if you created each reference by calling new.

You need to override equals, hashCode, and toString according to "Effective Java" to get the behavior you want.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

System.out.println(groupType) usually calls the toString() method on java.lang.Object and this prints:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Now, hashCode()may be a little bit misleading because if it's not overwritten then ...

the hashCode method defined by class Object does return distinct integers for distinct objects.

Quotes from java.lang.Object documentation.

Markus L
  • 932
  • 2
  • 20
  • 38