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.
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.
dereferencing (in java) = Action of accessing an object's features through a reference.
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.
equals
is a method of a class. int
is a primitive, not a class. Simply use ==
instead:
return n == thatInt.n;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With