eclipse 我怎样才能在原始类型(int)上解决这个等于
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33146329/
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
How can i fix this equals on primitive type(int)
提问by Caitlin Craik
heres my code for a library application
这是我的图书馆应用程序代码
package com.accenture.totalbeginner;
public class Person {
private String name;
private int maximumbooks;
public Person() {
name = "unknown name";
maximumbooks = 3;
}
public String getName() {
return name;
}
public void setName(String anyname) {
name = anyname;
}
public int getMaximumbooks() {
return maximumbooks;
}
public void setMaximumbooks(int maximumbooks) {
this.maximumbooks = maximumbooks;
}
public String toString() {
return this.getName() + " (" + this.getMaximumbooks() + " books)";
}
public boolean equals(Person p1) {
if(!this.getName().equals(p1.getName())) {
return false;
}
if(!this.getMaximumbooks().equals(p1.getMaximumbooks())) {
return false;
}
return true;
}
}
(!this.getMaximumbooks().equals(p1.getMaximumbooks()))
this is saying cannot invoke .equals on primitive type(int)
这是说不能在原始类型(int)上调用 .equals
I know what that means, but I have tried everything and I can't think how to correct it.
我知道这意味着什么,但我已经尝试了一切,但我想不出如何纠正它。
If you need any of the code from other classes let me know.
如果您需要其他课程的任何代码,请告诉我。
回答by Alexandre Beaudet
equals()
is used for Object
s (String
, Integer
, etc...)
equals()
用于Object
s ( String
, Integer
, 等等...)
For primitiveslike int
, boolean
, char
etc, you have to use ==
对于原语喜欢int
,boolean
,char
等等,你必须使用==
回答by Jens
getMaximumbooks()
returns a primitive type int
not an Object
. You have to compare it with ==
or in you case !=
(not equals
)
getMaximumbooks()
返回原始类型int
而不是Object
. 您必须将它与==
或在您的情况下!=
(不是equals
)进行比较
if (this.getMaximumbooks() != p1.getMaximumbooks())
{
return false;
}
return true;
回答by Yassin Hajaj
Just use ==
if you're comparing primitives.
只要使用==
如果您要比较的图元。
Also, try not to use getters
when working into the class because you have already access to all the fields (private
or not).
此外,getters
在进入课堂时尽量不要使用,因为您已经访问了所有字段(private
或没有)。
public boolean equals(Person p1)
{
return this.maximumBooks == p1.getMaximumBooks();
}