Sugihara
Sugihara

Reputation: 1101

Java compare this class to that class for equality

My assignment is to override the method equals(). I have a few concerns using Stack12<E> that = (Stack12<E>)o; and o instanceof Stack12. I am wonder are they bad practice, especially how I using that in the for-loop feels a little not right to me.

Is there another way to compare the this class to some other object? Or is my compare method robust enough?

  public boolean equals(java.lang.Object o){
  if(o == this) return true;
  if(o == null || !(o instanceof Stack12)){
     return false;
  }

  Stack12<E> that = (Stack12<E>)o;
  if(this.size != that.size || this.capacity != that.capacity ){
     return false;
  }
  for(int i = 0; i < this.size; i++){
     if( that.stack[i] != this.stack[i] ){
        return false;
     }
  }
  return true;
 }

Upvotes: 2

Views: 420

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

One caveat I'd add is that whenever you override equals(...), you will also want to override hashCode(). I agree that seeing instanceof overused makes me worry about code smell, but I think that you have no choice but to use instanceof in this situation. As for casting to generic type, I may be wrong, but at run-time, generics really don't exist, so it may be moot.

One potentially major issue I see though is that you're using == in your for loop. If your stack array uses objects, you should use equals(...) inside the loop. The fact that your class is generic suggests that the stack array does hold objects, but I'm not sure since we don't see this.

Upvotes: 5

Related Questions