简体   繁体   English

为什么Java autobox int for Integer for .equals(Object)方法?

[英]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. 我正在研究一些java类,并且正在重写.equals(Object)方法来测试我的类的整数变量,并且当它抛出错误说我无法使用原始类型int时,我很惊讶,当我确定它说在java docs中,编译器会自动将autobox基本类型转换为方法的包装类型。

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. 我想“this.myInt”是一个int而不是一个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()); 你可以使用return (this.myInt==mc.getMyInt()); . the equals() method is only defined for Objects. equals()方法仅为Objects定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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