Java 新手并出现错误“int 无法取消引用”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15857377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New to Java and have the error "int cannot be dereferenced"
提问by Tian
I'm new to java and I've been working on this exercise for a while, but keep receiving the error: int cannot be dereferenced. I saw couple of similar questions but still cannot figure out my own case. Here is the complete codes:
我是 Java 新手,我已经在这个练习上工作了一段时间,但一直收到错误:int 不能被取消引用。我看到了几个类似的问题,但仍然无法弄清楚我自己的情况。这是完整的代码:
package inclass;
class OneInt {
int n;
OneInt(int n) {
this.n = n;
}
@Override public boolean equals(Object that) {
if (that instanceof OneInt) {
OneInt thatInt = (OneInt) that;
return n.equals(thatInt.n); // error happens here
} else {
return false;
}
}
public static void main(String[] args) {
Object c = new OneInt(9);
Object c2 = new OneInt(9);
System.out.println(c.equals(c2));
System.out.println(c.equals("doesn't work"));
}
}
Thank you very much for helping me with this little trouble.
非常感谢你帮我解决了这个小麻烦。
回答by Bernhard Barker
equals
is a method of a class. int
is a primitive, not a class. Simply use ==
instead:
equals
是一个类的方法。int
是一个原始类型,而不是一个类。只需使用==
:
return n == thatInt.n;
回答by Code-Apprentice
To compare int
s, just use the ==
operator:
要比较int
s,只需使用==
运算符:
if (n == thatInt.n)
Note that int
is not a class, so you can neveruse the .
operator with an int
variable.
请注意,这int
不是一个类,因此您永远不能将.
运算符与int
变量一起使用。