-4

I am seeing a strange issue. I have an object, which has a few instance variables, one of which is numeric. This object came out of a socket using ObjectInputStream's readObject(), so it should have been deserialized. However, when i compare it with another object which has the exact same number for that field, using == , it doesn't match. Note: I am not comparing objects, just the integer instance variable, using a getter. Print statements just before the comparison, show that they're exactly the same.

    System.out.println("New book id:"+newBook.getId());
for (Book p: listOfBooks) {
    System.out.println("CurrentBook's id:"+p.getId());
    if (newBook.getId() == p.getId()) {
        System.out.println("Matched CurrentBook's id:"+p.getId()) 
            }
    }

Thanks Ted Hopp, yes, i guess the behaviour is inconsistent for Integer comparisons with ==. I realised that the fields were Integer, not int, and it worked before, so was very confusing why it no longer worked.

stumped
  • 491
  • 3
  • 6
  • 19

3 Answers3

3

Comparing numeric objects (Integer, etc.) using == can give inconsistent results. Integer, for instance, will autobox all values between -128 and +127 to cached values, but values outside that range may or may not be cached, depending on the implementation. Thus,

Integer.valueOf(-45) == Integer.valueOf(-45)

will be true, but

Integer.valueOf(-145) == Integer.valueOf(-145)

will usually be false.

For numeric quantities, you should either use .equals() or else extract the primitive values (int, long, etc.) before using ==

num1.intValue() == num2.intValue()
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

readObject() returns an object, so be sure to cast it to an int

http://docs.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject()

alex_milhouse
  • 891
  • 1
  • 13
  • 31
0

Print statements just before the comparison, show that they're exactly the same.

I think Alex Rellim is right. And the Print statements reads the object's toString method. That's why you see the numbers are the same. If you use a debugger, check the object's type.

Edit (after OP's code's being pasted): Could this be your problem? Using == operator in Java to compare wrapper objects

Community
  • 1
  • 1
sarahTheButterFly
  • 1,894
  • 3
  • 22
  • 36