4

Why do I experience the following behaviour when comparing a Java integer to a Python one of the same value in Jython?

>>> from java.lang import Integer
>>> 10 == Integer(10)
False
>>> 10 <= Integer(10)
True
>>> 10 >= Integer(10)
True

Okay, so I find it weird that both <= and >= operators evaluate as expected, yet == does not... So now lets check implicit conversions between Java & Jython types:

>>> i = Integer(10)
>>> i == 10
False

What about other Java classes I hear you say? Lets try:

>>> from java.lang import Boolean
>>> Boolean(0) == False
False
>>> Boolean(0) == True
False
>>> Boolean(0)  # lets just check it is a Java false not a Python one
false

Am I missing something or is it just as simple as the __eq__ magic (dunder) methods are broken for the Java classes (I am using Jython 2.7)?

EDIT

Thanks to weston for clarifying that in java 10 == new Integer(10) evaluates as true and therefore the question is not a duplicate of What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Liam Deacon
  • 904
  • 1
  • 9
  • 25
  • 2
    Possible duplicate of [What is the difference between == vs equals() in Java?](http://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java) – Julien Feb 02 '17 at 13:20
  • 1
    Not a duplicate, that question does not explain this because this behavior is not seen in java `10 == new Integer(10)` is true in java. – weston Feb 02 '17 at 13:58

1 Answers1

5

Essentially it's because == compares references for boxed types, not the actual values.

But to muddy the waters further <= and >= will auto-unbox any boxed operands.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 2
    So where only one side is boxed, jython `==` will box the other side, unlike java which unboxes the boxed side. Of course that would explain the behavior, but do you have a reference? – weston Feb 02 '17 at 14:02
  • 2
    jython.org: ["these operators have no significant difference to that of Java."](http://www.jython.org/jythonbook/en/1.0/OpsExpressPF.html#comparison-operators) Seems odd then that this departure is not noteworthy. – weston Feb 02 '17 at 14:05