Ah. After checking the javadoc it all makes sense - if two objects are 'equal' then their hashcodes should be equal if you're going to use them in a hashtable. Pity that I didn't get any errors about equals() and hashcode() conflicting - that way I might have thought to check the hashcode spec on my own.

On 5/10/06, Fritz Meissner <[EMAIL PROTECTED]> wrote:
Wow, cool. I saw something about this online, but would've ignored the bit about overriding hashcode if I hadn't seen this example. Thanks.

Fritz

On 5/10/06, klutz <[EMAIL PROTECTED]> wrote:

When overriding the equals method one is required to also override
hashCode().

Check the JavaDoc for java.lang.Object... Much clearer than my
ramblings... :)

Here's some example code that produces the result you require...

The implementations of equals and hashcode is not null safe at all...
this is quick and dirty...

Cheers,
Renier

package sandbox;

import java.util.HashSet;

public class Test {

    public static void main(String[] args) {

        HashSet<Proposition> testSet1 = new HashSet<Proposition>();
        HashSet<Proposition> testSet2 = new HashSet<Proposition>();

        Proposition prop1 = new Proposition("test");
        Proposition prop2 = new Proposition("goneElement");
        Proposition prop3 = new Proposition("test");

        testSet1.add (prop1);
        testSet1.add(prop2);

        testSet2.add(prop3);

        testSet1.retainAll(testSet2);

        System.out.println(testSet1.size());

    }

    private static class Proposition {

        private String name = null;

        public Proposition( String name ) {
            this.name = name;
        }

        public boolean equals( Object o ) {
            if ( o == null ) {
                return false;
            }
            if ( ! ( o instanceof Proposition ) ) {
                return false;
            }
            return this.name.equals (((Proposition)o).name);
        }

        public int hashCode() {
            return name.hashCode();
        }

    }

}




--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CTJUG Forum" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/CTJUG-Forum
For the ctjug home page see http://www.ctjug.org.za
-~----------~----~----~----~------~----~------~--~---

Reply via email to