2

I need to create new Range object, changing only one (lower or upper) bound. Other bound must be unchanged.

What is most convenient way to do that?

I see method com.google.common.collect.Range#range(C lower, BoundType lowerType, C upper, BoundType upperType), but when I need to change lower, I must copy upper value from my range - and be careful if upperBound exist at all.

It looks rather ugly (example below). And I need similar code for changing upper bound. Is there easier way to do so?

if (range.hasUpperBound()) {
    range = Range.range(value, BoundType.CLOSED, range.upperEndpoint(), timeSpend.upperBoundType());
} else {
    range = Range.upTo(value, BoundType.CLOSED);
}
Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113

2 Answers2

2

I came with following, generic helper methods (they create double-closed range, which I need)

 private static <T extends Comparable> Range<T> withLowerBound(Range<T> range, 
                                                              T lowerEndpoint) {
    if (range.hasLowerBound()) {
        return Range.closed(lowerEndpoint, range.upperEndpoint());
    } else {
        return Range.atLeast(lowerEndpoint);
    }
}

private static <T extends Comparable> Range<T> withUpperBound(Range<T> range,
                                                            T upperEndpoint) {
    if (range.hasLowerBound()) {
        return Range.closed(range.lowerEndpoint(), upperEndpoint);
    } else {
        return Range.atMost(upperEndpoint);
    }
}

Because Range is immutable, they must be used as follows

myRange= setLowerBound(myRange, newLowerValue);
myRange= setUpperBound(myRange, newUpperValue);
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
  • 2
    Just a minor note, instead of calling it `setLowerBound` and `setUpperBound`, I think `withLowerBound` and `withUpperBound` are more appropriate. – habsq Jul 10 '15 at 13:24
1

Range is immutable, you can only create a new Range based on another Range. Like what you gave in your example.

With that saying, you can always create a helper method.

habsq
  • 1,827
  • 16
  • 17