简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM