Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 878
Tian Avatar asked Apr 07 '13 00:04

Tian


People also ask

What does it mean Cannot be dereferenced?

Dereferencing means the action of accessing an object's features through a reference. Performing any dereferencing on a primitive will result in the error “X cannot be dereferenced”, where X is a primitive type.

What can be dereferenced in Java?

dereferencing (in java) = Action of accessing an object's features through a reference.

Which variable can be dereferenced?

Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.


1 Answers

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

return n == thatInt.n;
like image 103
Bernhard Barker Avatar answered Nov 15 '22 02:11

Bernhard Barker