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

2020-04-21 03:26发布

问题:

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();
}