简体   繁体   中英

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.

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. 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).

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. Of course you should have hash and equals methods implemented.

There is no get method on java sets .

You could refactor and add all elements to hashmap - Map has the get method.

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.

I had a similar problem. I solved it by implementing the Set interface using a Map. 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();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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