Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:

After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?

In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.

3 Answers
3

Intersection is done with Collection.retainAll; subtraction with Collection.removeAll; union with Collection.addAll. In each case, as Set will act like a set and a List will act like a list. As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.

Are you looking for java.util.Set interface (and its implementations HashSet and TreeSet (sorted))?
The interface defines removeAll(Collection c) which looks like substract(), and retainAll(Collection c) which looks like intersection.

Good answer. However, these will modify one of the two sets. If Ross wants a third set containing the solution, He'll need to clone one first and use it as the implicit variable.
–
Chris CudmoreOct 2 '08 at 19:26

mmyer, thanks for pointing that out, I still have a tab opened on Java 1.5 docs to play with Processing, and I am too often bitten by these darn framesets. Link is fixed.
–
PhiLhoOct 3 '08 at 9:45