Java: omitting a data member from the equals method.

Posted by cchampion on Stack Overflow See other posts from Stack Overflow or by cchampion
Published on 2010-03-14T01:15:05Z Indexed on 2010/03/14 1:25 UTC
Read the original article Hit count: 319

Filed under:
|
|
|
|
public class GamePiece {
    public GamePiece(char cLetter, int nPointValue) {
        m_cLetter=cLetter;
        m_nPointValue=nPointValue;
        m_nTurnPlaced=0;    //has not been placed on game board yet.
    }

    public char GetLetter() {return m_cLetter;}
    public int GetPointValue() {return m_nPointValue;}
    public int GetTurnPlaced() {return m_nTurnPlaced;}

    public void SetTurnPlaced(int nTurnPlaced) { m_nTurnPlaced=nTurnPlaced; }

    @Override
    public boolean equals(Object obj) {
        /*NOTE to keep this shorter I omitted some of the null checking and instanceof stuff. */
        GamePiece other = (GamePiece) obj;

        //not case sensitive, and I don`t think we want it to be here.
        if(m_cLetter != other.m_cLetter) {
            return false;
        }

        if(m_nPointValue != other.m_nPointValue) {
            return false;
        }
        /* NOTICE! m_nPointValue purposely omitted.  It does not affect hashcode or equals */

        return true;
    }

    @Override public int hashCode() {
        /* NOTICE! m_nPointValue purposely omitted.  It should not affect hashcode or equals */
        final int prime = 41;
        return prime * (prime + m_nPointValue + m_cLetter);
    }

    private char m_cLetter;
    private int m_nPointValue;
    private int m_nTurnPlaced;//turn which the game piece was placed on the game board.  Does not affect equals or has code!
}

Consider the given piece of code. This object has been immutable until the introduction of the m_nTurnPlaced member (which can be modified by the SetTurnPlaced method, so now GamePiece becomes mutable).

GamePiece is used in an ArrayList, I call contains and remove methods which both rely on the equals method to be implemented.

My question is this, is it ok or common practice in Java for some members to not affect equals and hashcode? How will this affect its use in my ArrayList? What type of java Collections would it NOT be safe to use this object now that it is mutable? I've been told that you're not supposed to override equals on mutable objects because it causes some collections to behave "strangely" (I read that somewhere in the java documentation).

© Stack Overflow or respective owner

Related posts about java

Related posts about equals