I am looking for a Java implementation of a data structure which holds a collection of elements for which a partial ordering is defined, and which allows one to iterate over those elements in some topological order (any of the possible orderings is fine; preferably a stable ordering as the contents of the collection changes).
Ideally it would implement a Collection<E>
, Set<E>
, or SortedSet<E>
interface and support all of the methods on the interface. In terms of specifying the total ordering, the collection could be instantiated with a Comparator<E>
, and the comparator could throw an exception (ClassCastException
?) if two elements being compared are not ordered with respect to each other. As a bonus, it would throw an exception if an element being inserted would produce an ordering anomaly (a cycle in the ordered graph of elements).
So yeah, what I want is a topological sort, but I would like a collection object that maintains that sort order with every insertion/removal, similarly to how SortedSet maintains a collection in sorted order.
Does something like this exist? In some open source library?
References:
http://en.wikipedia.org/wiki/Partially_ordered_set
http://en.wikipedia.org/wiki/Topological_sorting
Update
I ended up going with a different approach for my problem where I won't need a poset, after realizing the performance implications of my requirements (and various other issues that I couldn't quite resolve, using the poset). Relying on the comparator to determine the ordering among elements means that for element insertion, I have to consult the comparator against every existing element, costing O(n) per insertion.
If performance were not very important (it is), and if the number of elements was bounded to something reasonable (it isn't), I think I would have taken the approach suggested by Willie, although perhaps with my own graph implementation and topological sort implementation to minimize dependencies.
Comparator
... "A comparison function, which imposes a total ordering on some collection of objects." – Meteorology