Thread:
 equals and hashCode another pattern proposal 
 nicolas_r   22 Sep 2006, 11:10 
 Re: equals and hashCode another pattern proposa... 
 simon_t   01 Nov 2006, 10:03 

Comment
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
From: nicolas_r (22 Sep 2006, 11:10) Replies: 1, Views: 27437
Subject: equals and hashCode another pattern proposal
Hello,

Here is an implementation of equals and hashCode that  
passes successfully the 3 tests listed above in the article:
 - "multiple new instances in set"
 - "equal to same object from other session"
 - "collections intact after saving"

I did not test it against the "use in a composite-id" test.

The principle is simple: 
The first time equals or hashCode is called, we check if the 
primary key (here getUserId()) is present or not.
If yes: we use it in equals/hashcode
If no: we use a UID (here _uidInEquals) during the entire life of this
instance 
       even when latter on this instance is assigned a primary key.

I'd be happy to get some feedbacks on this implementation (is it
acceptable or not ?)
<code>
    private boolean _freezeUseUidInEquals = false;
    private boolean _useUidInEquals = true;
    private java.rmi.dgc.VMID _uidInEquals = null;

    private void setEqualsAndHashcodeStrategy() {
        if (_freezeUseUidInEquals == false) {
            _freezeUseUidInEquals = true;
            _useUidInEquals = (getUserId() == null);

            if (_useUidInEquals) {
                _uidInEquals = new java.rmi.dgc.VMID();
            }
        }
    }

	public boolean equals(Object object) {
		if (this == object) {
			return true;
        }

        if((object == null) || (object.getClass() != this.getClass()))  {
            return false;
        }

		UserModel other = (UserModel) object;

        setEqualsAndHashcodeStrategy();

        if (_useUidInEquals) {
            return _uidInEquals.equals(other._uidInEquals);
        } else {
            return getUserId().equals(other.getUserId());
        }
	}

	public int hashCode() {
        setEqualsAndHashcodeStrategy();

        if (_useUidInEquals) {
            return _uidInEquals.hashCode();            
        } else {
            return getUserId().hashCode();
        }
	}
</code>
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
© Copyright 2006, Red Hat Middleware, LLC. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc. [Privacy Policy]