I am working on the equals() method for my sparse matrix class that I’m writing (part of a school project). I am constantly runnung into the issue that it won’t let me use any methods or other members specific to my class, because that(the name I used for the parameter to equals) has to be of the generic type Object in order to override Objects‘s equals() method. Even beyond that, I need to be able to use some of the methods of my SparseMatrix’s type parameter in order to really compare the equality, unless I can also figure ou. How can I write it to get around that obstacle?
I have a few ideas how I night do it, but none of them seem to work: I’ve triedcasting the parameter, I’ve tried overlading equals(), I’ve even tried some other stuff, but none of it seems to work.
This is what I have so far, but, as I said, I just can’t get it to work.
public boolean equals(Object that) {
if (that instanceof SparseMatrix<?>) {
if (this.xSize != that.xSize ||
this.ySize != that.ySize)
return false;
/* make some more comparisons that depend on specific
* members of my matrix class, etc...*/
}
return false;
}
I have tried searching SO for this, and while I was able to find a few that seemed to be asking the same thing, I couldn’t find any answers that actually explained how to do it.
When you have an object of a base class and you know which kind of subclass it is, you can convert it by downcasting it. Then you can call any methods specific to the subclass.
Should
onot be an instance of SparseMatrix or a class which extends/implements SparseMatrix (you already checked that, but let’s assume you didn’t) you would get a ClassCastException.