Java – clone and subtract sets – is this useful?
•
Java
private HashMap<DataObject,HashSet> AllDataObjects;
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(); }
Please note that I do not want to change alldataobjects. XML through this process I convert the keys of a set of alldataobjects (DataObjects I want to subtract from the set parameter) to HashSet to use clone, which should return a shallow copy, and then I can delete the set without affecting alldataobjects
Does this look good to you?
Solution
Create a new set and merge the set to be cloned as a parameter This avoids projection, so you won'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 is also worth noting that you should use set instead of HashSet as a parameter to avoid overburdening customers
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码