Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...