为什么 java.util.Set<V>接口不提供 get(Object o) 方法? [英] Why does the java.util.Set<V> interface not provide a get(Object o) method?

查看:16
本文介绍了为什么 java.util.Set<V>接口不提供 get(Object o) 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 Set 中只允许根据 .equals() 的任何对象的一个​​实例,并且如果您已经有一个等效的对象,您不应该需要"从 Set 中获取一个对象,但我会仍然喜欢有一个 .get() 方法,它返回 Set 中对象的实际实例(或 null),给定一个等效对象作为参数.

I understand that only one instance of any object according to .equals() is allowed in a Set and that you shouldn't "need to" get an object from the Set if you already have an equivalent object, but I would still like to have a .get() method that returns the actual instance of the object in the Set (or null) given an equivalent object as a parameter.

关于它为什么设计成这样的任何想法/理论?

Any ideas/theories as to why it was designed like this?

我通常不得不通过使用 Map 并使键和值相同或类似的东西来解决这个问题.

I usually have to hack around this by using a Map and making the key and the value same, or something like that.

我认为到目前为止人们还没有理解我的问题.我想要集合中已经存在的确切对象实例,而不是 .equals() 返回 true 的可能不同的对象实例.

I don't think people understand my question so far. I want the exact object instance that is already in the set, not a possibly different object instance where .equals() returns true.

至于为什么我想要这种行为,通常 .equals() 不会考虑对象的所有属性.我想提供一些虚拟查找对象并取回 Set 中的实际对象实例.

As to why I would want this behavior, typically .equals() does not take into account all the properties of the object. I want to provide some dummy lookup object and get back the actual object instance in the Set.

推荐答案

虽然纯度参数确实使方法 get(Object) 令人怀疑,但潜在的意图并没有实际意义.

While the purity argument does make the method get(Object) suspect, the underlying intent is not moot.

有各种类和接口族稍微重新定义了equals(Object).只需查看集合接口即可.例如,ArrayList 和 LinkedList 可以相等;它们各自的内容只需相同且顺序相同即可.

There are various class and interface families that slightly redefine equals(Object). One need look no further than the collections interfaces. For example, an ArrayList and a LinkedList can be equal; their respective contents merely need to be the same and in the same order.

因此,在集合中找到匹配元素有很好的理由.也许更清晰的表达意图的方法是使用像

Consequently, there are very good reasons for finding the matching element in a set. Perhaps a clearer way of indicating intent is to have a method like

public interface Collection<E> extends ... {
  ...
  public E findMatch(Object o) throws UnsupportedOperationException;
  ...
}

请注意,此 API 具有比 Set 中更广泛的价值.

Note that this API has value broader that within Set.

至于问题本身,我没有任何关于为什么省略这样一个操作的理论.我会说最小生成集参数不成立,因为集合 API 中定义的许多操作都是为了方便和效率.

As to the question itself, I don't have any theory as to why such an operation was omitted. I will say that the minimal spanning set argument does not hold, because many operations defined in the collections APIs are motivated by convenience and efficiency.

这篇关于为什么 java.util.Set&lt;V&gt;接口不提供 get(Object o) 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆