Which of the following pieces of logic could be used in the method that implements Comparable? Assume that the method is passed Object a, which is really a ChessPiece. Also assume that ChessPiece has a method called returnType which returns the type of the given piece. Only one of these answers has correct logic.
a) if (this.type < a.returnType( )) return –1;b) if (this.type = = a.returnType( )) return 0;
c) if (this.type.equals(a.returnType( )) return 0;
d) if (a.returnType( ).equals(“King”)) return -1;
e) if (a.returnType( ).equals(“Pawn”)) return 1;
Consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store “King”, “Queen”, “Bishop”, etc and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: “Pawn” is a lesser piece to a “Knight” and a “Bishop”, “Knight” and “Bishop” are equivalent for this example, both are lesser pieces to a “Rook” which is a lesser piece to a “Queen” which is a lesser piece to a “King.”
Answer: c.
Explanation: If the type of this piece and of a are the same type, then they are considered equal and the method should return 0 to indicate this. Note that this does not cover the case where this piece is a “Knight” and a is a “Bishop”, so additional code would be required for the “equal to” case. The answer in b is not correct because it compares two Strings to see if they are the same String, not the same value. The logic in d and e are incorrect because neither of these takes into account what the current piece is, only what the parameter’s type is. In d, if a is a “King”, it will be greater than this piece if this piece is not a “King”, but will be equal if this piece is a “King” and similarly in e, it does not consider if this piece is a “Pawn” or not. Finally, a would give a syntax error because two Strings cannot be compared using the “<” operator.