Frage

I'm eager to use Guava's RangeSets in my program. Despite the features of adding and merging of ranges, i'm also interested in the "size" of my ranges.

Some remarks:

  • no ranges i'm interested in are infinite!
  • all ranges i'm using are of the bound-type "closedOpen"
  • the underlying use-case is a discrete time-space (size = summed up time-ticks)

This seems to be something which is not built-in (or i didn't see it) and i'm wondering if there is a clear reason against this conceptionally (which means i should not implement some getSize() function myself) or not.

Let's have a look at my use-case:

RangeSet<Integer> usageTicks = TreeRangeSet.create();
usageTicks.add(Range.closedOpen(3, 7));
usageTicks.add(Range.closedOpen(12,18));
usageTicks.add(Range.closedOpen(18, 23));

int size = usageTicks.hypotheticalGetSizeFunction(); // size = 15

Is there any reason against the following:

Set<Range<Integer>> setOfRanges = usageTicks.asRanges();
int sum = 0;
for(Range<Integer> range : setOfRanges)
    sum += (range.upperEndpoint() - range.lowerEndpoint());
War es hilfreich?

Lösung

Guava's Range only require one thing of its enclosed types: that they implement Comparable.

But not all which implement Comparable have a notion of distance. How would you measure the distance between two Strings, for instance?

This is why Guava also has DiscreteDomain and ContiguousSet; with the former you have methods such as next(), prev() and distance(), which is what you are interested in here. Guava's site has an article on it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top