Shadow
Shadow

Reputation: 4006

Why doesn't Java autobox int to Integer for .equals(Object) method?

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()));
}

Upvotes: 4

Views: 733

Answers (2)

Jonatan Cloutier
Jonatan Cloutier

Reputation: 929

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

Upvotes: 5

TheLostMind
TheLostMind

Reputation: 36304

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

Upvotes: 1

Related Questions