如何在不修改公共接口的前提下将类内部int替换为BigInteger
适配BigInteger的改造方案
核心改造逻辑
- 仅修改私有成员变量类型,不触动任何对外公开的构造函数、方法签名
- 内部运算全部替换为BigInteger对应的API,入参出参涉及对外暴露的部分自动做int和BigInteger的类型转换
完整改造后代码
import java.math.BigInteger; public class RatNum { // 私有字段修改为BigInteger类型,不影响对外接口 private BigInteger numerator; private BigInteger denominator; // 公共构造函数签名完全保留,仅修改内部赋值逻辑 public RatNum(){ this.numerator = BigInteger.ZERO; this.denominator = BigInteger.ONE; } public RatNum(int a){ this.numerator = BigInteger.valueOf(a); this.denominator = BigInteger.ONE; } // 原有私有gcd方法直接实现BigInteger版本的求最大公约数逻辑 private RatNum gcd(BigInteger a, BigInteger b){ // 欧几里得算法实现 while (!b.equals(BigInteger.ZERO)) { BigInteger temp = b; b = a.mod(b); a = temp; } // 约分逻辑示例,可根据业务需求调整返回值 BigInteger gcdVal = a; this.numerator = this.numerator.divide(gcdVal); this.denominator = this.denominator.divide(gcdVal); // 保证分母始终为正 if (this.denominator.compareTo(BigInteger.ZERO) < 0) { this.numerator = this.numerator.negate(); this.denominator = this.denominator.negate(); } return this; } // 原有其他公共方法只需调整内部逻辑,签名完全不变 // 示例:原有公共方法返回分子的int值,签名不变,内部做类型转换 public int getNumerator() { return numerator.intValue(); } public int getDenominator() { return denominator.intValue(); } }
注意事项
- 如果内部运算结果超出int范围,对外返回int值的时候会出现精度丢失,可根据业务需求新增非对外的内部方法处理大数值返回的场景
- 所有内部算术运算禁止使用
+、-、*、/等运算符,全部替换为BigInteger对应的add()、subtract()、multiply()、divide()方法
内容的提问来源于stack exchange,提问作者Bosse2004
相关产品推荐
相关产品推荐

