The Java API is badly in need of editting.
I just bumped into Collection.equals(Object) method, which contains this gem:
Thus, a custom equals method for a collection class that implements neither the
ListnorSetinterface must return false when this collection is compared to any list or set. (By the same logic, it is not possible to write a class that correctly implements both theSetandListinterfaces.)
So a list that guaranties uniqueness would have to be a Set or a List, but absolutely cannot be both. At least, not without violating the API.
The intuitive API to me is to have the Collection interface require that the Collection.equals(Object) method to return true iff the argument is a collection whose Iterator returns the same elements in the same order as this.iterator(). This would mean that collections with different add/remove behavior could be equals to eachother, but that’s already true — a synchronized ArrayList is equals to a unsynchronized ArrayList is equals to a typed List is equals to a LinkedList by definition, as long as they return the same elements in the same order.
The real fun is that the note in the Collections class is actually wrong. If you look at Set.equals(Object), it requires that the parameter is equals to this iff they are both sets, and if the parameter has the same size as this and if all the elements of this are contained in the parameter. If you look at List.equals(Object), this is equals to the parameter iff they are both lists, and if they return the same elements in the same order. I see nothing in these definitions that says you can’t satisfy both of them at the same time.
Related posts: