commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From (Peter Ko├ček)
Subject [collections] Question about CollectionUtils semantics
Date Tue, 28 Jan 2003 00:36:51 GMT
----- Original Message -----
From: "Greg Zoller"
Subject: Re: Question about CollectionUtils semantics

> I think the reason your example works is that you're using String-typed
> variables...

No. That's not really the reason why.

> I have another example that uses another object:
> public class Hey {
>     private String id;
>     public Hey( String id ) { = id; }
>     public boolean equals( Object obj ) {
>         Hey otherHey = (Hey) obj;
>         if( ) )
>             return true;
>         return false;
>     }
>     public String toString() { return id; }
> }

Hey - where is your #hashCode implementation? You forgot to fulfill the contract
mentioned in . Years
before the first Java programmer forgot to fulfill the contract, programmers of
other languages did the same:
D - and still there's no end in sight. If you didn't know this problem at all,
you should have a look into the book "Effective Java" by Joshua Bloch.

Incomplete object implementations which override #equals but don't override
#hashCode cannot be used within HashSets and HashMaps. The hashing algorithm
will fail then.

The CollectionUtils#intersection implementation relies on the use of HashMaps.
The Collection#retainAll doesn't use hashing, so it can't fail. But if you try
to use incomplete object implementations, your code will run into large problems
sooner or later, because hashing is used so often.

> Regards,
> Greg


View raw message