How can i fix this equals on primitive type(int)

非 Y 不嫁゛ 提交于 2020-01-11 12:18:51

问题


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)

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.


回答1:


equals() is used for Objects (String, Integer, etc...)

For primitives like int, boolean, char etc, you have to use ==




回答2:


getMaximumbooks() returns a primitive type int not an Object. You have to compare it with == or in you case != (not equals)

if (this.getMaximumbooks() != p1.getMaximumbooks())
{
    return false;
}
return true;



回答3:


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).

public boolean equals(Person p1)
{
    return this.maximumBooks == p1.getMaximumBooks();
}


来源:https://stackoverflow.com/questions/33146329/how-can-i-fix-this-equals-on-primitive-typeint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!