我写了一个类来检查两个整数间隔是否重叠。但是我不太喜欢这个解决方案。我认为有可能以更好和更简单的方式做到这一点。
public class IntegerInterval implements Interval {
private Integer start;
private Integer end;
public IntegerInterval(Integer start, Integer end) {
this.start = start;
this.end = end;
}
public Integer getStart() {
return start;
}
public Integer getEnd() {
return end;
}
public boolean isOverlapping(IntegerInterval other) {
if (other != null) {
return isInInterval(start, other) || isInInterval(end, other)
|| isInInterval(other.start, this) || isInInterval(other.end, this);
}
return false;
}
public boolean isInInterval(Integer number, IntegerInterval interval) {
if (number != null && interval != null) {
if(interval.getStart() == null && interval.getEnd() != null) {
return number.intValue() <= interval.getEnd().intValue();
}
if(interval.getStart() != null && interval.getEnd() == null) {
return number.intValue() >= interval.getStart().intValue();
}
if(interval.getStart() == null && interval.getEnd() == null) {
return true;
}
return interval.getStart() <= number && number <= interval.getEnd();
}
else if(number == null && interval != null) {
return interval.getStart() == null && interval.getEnd() == null;
}
return false;
}
}