I am using IntelliJ IDEA 2018.1.3 Ultimate Edition, and need to compare to large integers (large enough to not fit into a long
, for example 20180531234240565494
) represented as strings:
public int compareNumeric(String compareTo) {
return new BigInteger(version).compareTo(new BigInteger(compareTo));
}
This is the solution proposed here, which I always thought was the correct way to create a BigInteger
from a String
.
However, IntelliJ gives the following warning, through a Sonar plugin:
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 ExampleString 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);
First of all, I don't see the constructor being deprecated in Java 9, is Sonar wrong here?
Am I doing the comparison wrong and triggered a false positive, or should the comparison be made in some other way?
The only other way I can think of is to compare the strings directly, but that would also force me to first check that the strings are numeric.