Skip to main content

Collections should use separate interface for comparison

No replies
tsinger
Offline
Joined: 2003-06-10
Points: 0

Currently, collections compare objects by obj1.equals(obj2).
But from time to time, one wants to add/remove the objects to/from the collection with == comparison. Please note, that one not always has the choice to override the equals-method of the objects.

I suggest, that one could pass an instance of EqualComparator to the constructor of ArrayList, LinkedList and so on, which defines how the objects are compared. The EqualComparator would look like:

public interface EqualComparator {</p>
<p>  boolean areEqual(Object object1, Object object2);</p>
<p>  EqualComparator IDENTITY = new EqualComparator() {<br />
    public boolean areEqual(Object object1, Object object2) {<br />
      return object1 == object2;<br />
    }<br />
  };</p>
<p>  EqualComparator EQUALS = new EqualComparator() {<br />
    public boolean areEqual(Object object1, Object object2) {<br />
      return (object1 == object2)<br />
          || (object1 != null && object1.equals(object2));<br />
    }<br />
  };<br />
}

Of course, the existing constructors would use EqualComparator.EQUALS for compatibility reasons.

--
Tom