Search code examples
javacollectionsclonesetsubtraction

Cloning and subtracting sets - does this work?


private HashMap<DataObject, HashSet> AllDataObjects;

...

/** Returns all DataObject elements that are NOT in the specified set. */
private DataObject[] invert( HashSet<DataObject> set )
{
    HashSet<DataObject> keys = (HashSet) AllDataObjects.keySet();
    keys = (HashSet) keys.clone();

    keys.removeAll( set );

    return (DataObject[]) keys.toArray();
}

Note that I don't want to alter AllDataObjects through this process. I casted the set of AllDataObjects' keys (which are the DataObjects I want the set parameter to subtract from) into a HashSet to use clone, which supposedly returns a shallow copy that I can then remove set from without affecting AllDataObjects.

Does this look right to you?


Solution

  • Create a new set and give the one to be cloned as an argument. This avoids casting and so you don't lose generics.

    private DataObject[] invert( Set<DataObject> set ){
        Set<DataObject> keys = new HashSet<DataObject>(AllDataObjects.keySet());
        keys.removeAll( set );
        return keys.toArray(new DataObject[]{});
    }
    

    It's also worth noting that you should use Set rather than HashSet for the parameter so as to not overly burden your clients.