我正在研究一些java类,并且重写了.equals(Object)测试我的类的整数变量的方法,当它发出错误说我无法使用原始类型int时,我很惊讶,当我确定它在java文档中说编译器会自动将原始类型自动放映到方法的包装类型中.
public boolean equals(Object o)
{
if (!(o instanceof myClass))
return false;
myClass mc = (myClass)o;
return (this.myInt.equals(mc.getMyInt()));
}
Run Code Online (Sandbox Code Playgroud)
我想"this.myInt"是一个int而不是一个Integer.自动装箱可以在参数中使用.这是一些例子
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
584 次 |
| 最近记录: |