0

I am noticing a weird behavior when I perform some basic checks using objects that have been .initialize()'ed using Hibernate.

The following 'if condition' fails even when it is supposed to pass:

 for (int j = 0; j < trcList.size(); j++) { if (trcList.get(j).getABC().getId() == abc.getId()) { //do something break; } } 

However if I change it slightly, it passes where expected. In the snippet below, I grab the LHS value in a local variable and use that for comparison:

 for (int j = 0; j < trcList.size(); j++) { int x = trcList.get(j).getABC().getId(); if (x == abc.getId()) { //do something break; } } 

trcList is an ArrayList created from an array of objects grabbed from a database using hibernate. Various fields in those objects including 'ABC' have been Hibernate.initialize()'ed.

 Session session = null; try { session = HibernateUtil.initializeHibernateConnection(session); Criteria cr = ... //specify search criteria List results = cr.list(); TRC[] trcArray = new TRC[results.size()]; for (int i = 0; i < results.size(); i++) { trcArray[i] = (TRC) results.get(i); if (trcArray[i].getABC() != null) { Hibernate.initialize(trcArray[i].getABC()); } } session.getTransaction().commit(); return trcArray; } catch (RuntimeException re) { log.error("get failed", re); throw re; } 
2
  • What does the method getID() return? Commented Jan 21, 2014 at 11:11
  • getId() returns the row id (primary key) from the table (an integer) Commented Jan 21, 2014 at 14:40

1 Answer 1

2

I suspect trcList.get(j).getABC().getId() is java.lang.Integer and hence it should be compared with equals()

if (trcList.get(j).getABC().getId().equals(abc.getId())) { } 

Below test will assert the same

Integer i = new Integer(1); //set to 1 Integer j = new Integer(1); //also set to 1 System.out.println(i == j); //false, because it is reference comparison System.out.println(i.equals(j)); //true 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.