[英]How can i fix this equals on primitive type(int)
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.如果您需要其他课程的任何代码,请告诉我。
equals()
is used for Object
s ( String
, Integer
, etc...) equals()
用于Object
s( String
, Integer
等)。
For primitives like int
, boolean
, char
etc, you have to use ==
对于
int
, boolean
, char
等原语 ,您必须使用==
getMaximumbooks()
returns a primitive type int
not an Object
. getMaximumbooks()
返回原始类型int
而不是Object
。 You have to compare it with ==
or in you case !=
(not equals
) 您必须将其与
==
进行比较,或者在您遇到的情况下!=
(不equals
)
if (this.getMaximumbooks() != p1.getMaximumbooks())
{
return false;
}
return true;
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
或非private
)。
public boolean equals(Person p1)
{
return this.maximumBooks == p1.getMaximumBooks();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.