Reputation: 4006
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
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
Reputation: 36304
You could just use return (this.myInt==mc.getMyInt());
. the equals()
method is only defined for Objects.
Upvotes: 1