gpt4 book ai didi

java - new BigInteger(String) 发出 Sonar 警告

转载 作者:行者123 更新时间:2023-11-30 07:46:21 28 4
gpt4 key购买 nike

我正在使用 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 给出了 the following warning ,通过 Sonar 插件:

Constructors should not be used to instantiate "String", "BigInteger", "BigDecimal" and primitive-wrapper classes

squid:S2129
Constructors for Strings, BigInteger, BigDecimal and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf for everything else.
Further, these constructors are deprecated in Java 9, which is an indication that they will eventually be removed from the language altogether.

Noncompliant Code Example

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/>

Compliant Solution

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 在这里错了吗?

我是不是做错了比较并触发了误报,还是应该以其他方式进行比较?

我能想到的唯一其他方法是直接比较字符串,但这也会迫使我首先检查字符串是否为数字。

最佳答案

你遇到了这个问题SONARJAVA-2740这已在最新的 SonarJava 版本中得到修复,应该会在几天内公开发布。

关于java - new BigInteger(String) 发出 Sonar 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695355/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com