Tian
Tian

Reputation: 63

New to Java and have the error "int cannot be dereferenced"

I'm new to java and I've been working on this exercise for a while, but keep receiving the error: int cannot be dereferenced. I saw couple of similar questions but still cannot figure out my own case. Here is the complete codes:

package inclass;

class OneInt {
  int n;

  OneInt(int n) {
    this.n = n;
  }

  @Override public boolean equals(Object that) {
    if (that instanceof OneInt) {
        OneInt thatInt = (OneInt) that;
        return n.equals(thatInt.n); // error happens here
    } else {
        return false;
    }
  }

  public static void main(String[] args) {
    Object c = new OneInt(9);
    Object c2 = new OneInt(9);
    System.out.println(c.equals(c2));
    System.out.println(c.equals("doesn't work"));
  } 
}

Thank you very much for helping me with this little trouble.

Upvotes: 5

Views: 12090

Answers (2)

Bernhard Barker
Bernhard Barker

Reputation: 55609

equals is a method of a class. int is a primitive, not a class. Simply use == instead:

return n == thatInt.n;

Upvotes: 7

Code-Apprentice
Code-Apprentice

Reputation: 83527

To compare ints, just use the == operator:

if (n == thatInt.n)

Note that int is not a class, so you can never use the . operator with an int variable.

Upvotes: 4

Related Questions