Interval类isSubsetOf方法计算逻辑错误,求定位问题原因
问题根源与修正
你的isSubsetOf方法逻辑完全搞反了判断方向。
你要实现的是判断传入的other区间是否是当前this区间的子集或完全相等,本质要求是:other的区间必须完全被this的区间包裹,也就是:
other的下界不能小于this的下界other的上界不能大于this的上界
但你当前的代码逻辑是:
return this.lowerBound - other.getLowerBound() <= 0 && this.upperBound - other.getUpperBound() >= 0;
拆解后等价于:
this.lowerBound <= other.getLowerBound()→ 这意味着this的下界比other的下界更小,完全不符合子集的判断逻辑(比如this是[1,5],other是[0,3],按这个逻辑会错误返回true,但other的下界超出了this的范围,根本不是子集)this.upperBound >= other.getUpperBound()→ 这部分逻辑是正确的
修正后的代码
直接调整判断条件的方向,同时用更直观的比较运算符(避免减法可能带来的整数溢出问题):
public boolean isSubsetOf(Interval other){ return other.getLowerBound() >= this.lowerBound && other.getUpperBound() <= this.upperBound; }
额外优化点
- 给方法加上
public修饰符,符合Java类成员的访问规范 - 直接使用比较运算符比减法更易读,还能规避极端场景下的整数溢出(比如
this.lowerBound为Integer.MIN_VALUE时,减法运算会溢出得到错误结果)
内容的提问来源于stack exchange,提问作者Finn A.
相关产品推荐
相关产品推荐

