简体   繁体   English

Java:有没有一种方法可以从Set的克隆中检索Set中的原始对象

[英]Java: Is there a way to retrieve, in a Set, an original object from its clone

I need to retrieve, in a Set, an original object from its clone. 我需要在Set中从其克隆中检索原始对象。

I would like to do something like: 我想做类似的事情:

Set<Object> mySet;
public void myModifyMethod(Object clone){
    if(mySet.contains(clone)){
        Object original = mySet.get(clone); // get method does not seem to exist

        // Modify original object
    }
}

I could not find any method in the Java SE 6 API to do that. 我在Java SE 6 API中找不到任何方法可以做到这一点。 The only way I can think about is to iterate over the whole set but this is not efficient at all (I was hoping to achieve O(1) from the HashSet, not the O(n) from a sequential search). 我能想到的唯一方法是遍历整个集合,但这根本没有效率(我希望从HashSet中获得O(1),而不是从顺序搜索中获得O(n))。

Is there a more efficient way to do that? 有更有效的方法吗?

The only solution I can think of is using a Map where the original object is both the key and the value, and then doing something like map.get(clone) to obtain the original. 我能想到的唯一解决方案是使用Map ,其中原始对象既是键又是值,然后执行诸如map.get(clone)来获取原始对象。 Of course you should have hash and equals methods implemented. 当然,您应该实现hashequals方法。

There is no get method on java sets . java集合上没有get方法

You could refactor and add all elements to hashmap - Map has the get method. 您可以重构所有元素并将其添加到哈希图中-Map具有get方法。

But why do you need to retrieve, in a Set, an original object from its clone , as you already have an instance of it, you are using that to check if it exists - just make sure you implement hashcode and equals appropriately. 但是为什么您需要在Set中从其clone中检索原始对象 ,因为您已经拥有它的实例,所以您正在使用该对象来检查其是否存在-只需确保实现哈希码并适当地进行相等即可。

I had a similar problem. 我有一个类似的问题。 I solved it by implementing the Set interface using a Map. 我通过使用Map实现Set接口来解决此问题。 Here is my implementation : 这是我的实现:

public final class HandleSet<E> extends AbstractSet<E> {

    private final HashMap<E, E> map;

    public HandleSet() {
        map = new HashMap<E, E>();
    }

    public E get(E o) {
        return map.get(o);
    }

    /* Implementation of Interface Set */

    @Override
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.containsKey(o);
    }

    @Override
    public boolean add(E o) {
        return map.put(o, o) == null;
    }

    @Override
    public boolean remove(Object o) {
        return o.equals(map.remove(o));
    }

    @Override
    public void clear() {
        map.clear();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM