Re: Set and .equals() semantics
Jaakko Kangasharju wrote:
What you're missing is that a Set implementation is not required to
store the objects that have been added to the Set anywhere, so while the
This is a good point, actually. I hadn't thought about it that way.
EnumSet can return the original object of course, because there is only
one object, but that's a specific case.
OK, I withdraw my previous whining. Map it is.
Here's my version. It needs more methods wrapped, but I think it's
pretty simple from here. Just pass the methods to the HashMap. Note I
have not actually tested the iterator. Hmm, once you count testing,
this is moving a tad beyond the "kindergarten" stage...
Maybe a new interface too, SetWithFind.... more code and testing...
package hashsetwithfind;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashSetWitFind<E> extends AbstractSet<E>
implements Set<E>
{
private final HashMap<E,E> set =
new HashMap<E,E>();
@Override
public boolean add( E e )
{
set.put(e, e);
return true;
}
@Override
public boolean contains( Object o )
{
return set.containsKey(o);
}
@Override
public boolean remove( Object b )
{
if( set.containsKey( b ) )
{
set.remove( b );
return true;
}
return false;
}
@Override
public Iterator<E> iterator()
{
return set.values().iterator();
}
@Override
public int size() {
return set.size();
}
public E find( E e )
{
return set.get(e);
}
}