4

I was working on some java classes, and was overriding the .equals(Object) method to test an integer variable of my class, and was surprised when it threw errors saying I could not use the primitive type int, when I was sure it said in the java docs that the compiler will automatically autobox primitive types into the wrapper types for methods.

public boolean equals(Object o)
{
    if (!(o instanceof myClass))
        return false;
    myClass mc = (myClass)o;
    return (this.myInt.equals(mc.getMyInt()));
}
Shadow
  • 3,926
  • 5
  • 20
  • 41
  • I'm guessing here, but I'm thinking when the method expects an `Integer` it will auto box but when it expects an `Object` (which you may know is intended to be an `Integer`) it will not – Richard Tingle Aug 24 '14 at 08:26
  • 5
    Autoboxing works on assignments (including parameter assignments). You are trying to use it in `this.myInt.equals(...)` where `myInt` is a primitive. There is no autoboxing available here. – Jim Garrison Aug 24 '14 at 08:28
  • 2
    assuming `getMyInt()` returns `int`, `this.myInt() == mc.getMyInt()` is fine here – jdphenix Aug 24 '14 at 08:28
  • As @Jim said, only assignment are concerned by autoboxing. There're no concept of `implicit` like in Scala that would allow what you expect ;) – Mik378 Aug 24 '14 at 08:32
  • 2
    "I was sure it said in the java docs that the compiler will automatically autobox primitive types into the wrapper types for methods." It doesn't. Have a look at what it really does say. – user207421 Aug 24 '14 at 08:37

2 Answers2

5

I suppose that "this.myInt" is a int and not a Integer. Autoboxing would work in the parameter. Here are some exemple

int a = 1;
int b = 1;
Integer c = 1;
Integer d = 1;

a.equals(b); // doesnt work as equals isn't define on int
c.equals(b); // work, c is an Integer/Object and b is autoboxed
c.equals(d); // work, both are Integer/Object
Jonatan Cloutier
  • 899
  • 9
  • 26
1

You could just use return (this.myInt==mc.getMyInt()); . the equals() method is only defined for Objects.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104