【发布时间】:2018-06-05 08:17:25
【问题描述】:
我使用的是 IntelliJ IDEA 2018.1.3 Ultimate Edition,需要与表示为字符串的大整数(大到不适合 long,例如 20180531234240565494)进行比较:
public int compareNumeric(String compareTo) {
return new BigInteger(version).compareTo(new BigInteger(compareTo));
}
这是here 提出的解决方案,我一直认为这是从String 创建BigInteger 的正确方法。
但是,IntelliJ 通过 Sonar 插件提供the following warning:
不应使用构造函数来实例化“String”、“BigInteger”、“BigDecimal”和原始包装类
鱿鱼:S2129
绝不应使用 Strings、BigInteger、BigDecimal 的构造函数和用于包装原语的对象。与简单地在字符串的情况下使用所需的值并在其他所有情况下使用 valueOf 相比,这样做不太清楚并且使用更多的内存。
此外,这些构造函数在 Java 9 中已被弃用,这表明它们最终将完全从该语言中删除。
不合规代码示例String empty = new String(); // Noncompliant; yields essentially "", so just use that. String nonempty = new String("Hello world"); // Noncompliant Double myDouble = new Double(1.1); // Noncompliant; use valueOf Integer integer = new Integer(1); // Noncompliant Boolean bool = new Boolean(true); // Noncompliant BigInteger bigInteger = new BigInteger("1"); // Noncompliant BigDecimal bigDecimal = new BigDecimal(1.1); // Noncompliant<br/>合规解决方案
String empty = ""; String nonempty = "Hello world"; Double myDouble = Double.valueOf(1.1); Integer integer = Integer.valueOf(1); Boolean bool = Boolean.valueOf(true); BigInteger bigInteger = BigInteger.valueOf(1); BigDecimal bigDecimal = BigDecimal.valueOf(1.1);
首先,我没有看到 the constructor 在 Java 9 中被弃用,Sonar 在这里错了吗?
我是否进行了错误的比较并触发了误报,还是应该以其他方式进行比较?
我能想到的唯一其他方法是直接比较字符串,但这也会迫使我首先检查字符串是否为数字。
【问题讨论】:
-
BigInteger.valueOf()的建议解决方案仅适用于可以适合long的值,所以我会忽略该警告(假设您的Strings 代表不适合的值long) -
@Stultuske 警告中提到这些构造函数已被弃用,但我没有看到
new BigInteger(String)被弃用。 -
@Eran 或假设您的字符串不是常量,在这种情况下您不知道它包含什么值。
-
@Stultuske 它们在 Java 10 中也没有被弃用。它们甚至没有计划在Java 11 中被弃用。更有可能
BigInteger被错误地扔进了与Integer和Long构造函数已 弃用的同一锅中。 -
顺便说一下,您的
20180531234240565494看起来有点像日期和时间字符串。你确定BigInteger是在这里使用的最佳类型吗?
标签: java sonarqube biginteger