为什么Set不提供获取与另一个元素相等的元素的操作?
Set<Foo> set = ...;
...
Foo foo = new Foo(1, 2, 3);
Foo bar = set.get(foo); // get the Foo element from the Set that equals foo
我可以问Set是否包含一个等于bar的元素,那么为什么我不能得到那个元素呢?:(
为了澄清,equals方法被重写,但它只检查其中一个字段,而不是所有字段。两个相等的Foo对象可以有不同的值,这就是为什么我不能只用Foo。
因为Set的任何特定实现都可能是随机访问,也可能不是。
You can always get an iterator and step through the Set, using the iterators' next() method to return the result you want once you find the equal element. This works regardless of the implementation. If the implementation is NOT random access (picture a linked-list backed Set), a get(E element) method in the interface would be deceptive, since it would have to iterate the collection to find the element to return, and a get(E element) would seem to imply this would be necessary, that the Set could jump directly to the element to get.
当然,Contains()可能需要做同样的事情,也可能不需要,这取决于实现,但名称似乎不会导致同样的误解。