String#toCharArray
allocates a new array. Calling charAt
is more efficient, because it avoids
creating a new array with a copy of the character data.
That is, prefer this:
boolean isDigits(String string) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
to this:
boolean isDigits(String string) {
// this allocates a new char[]
for (char c : string.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
Note that many loops over characters can be expressed using streams with
String#chars
or String#codePoints
, for example:
boolean isDigits(String string) {
string.codePoints().allMatch(Character::isDigit);
}
Suppress false positives by adding the suppression annotation @SuppressWarnings("LoopOverCharArray")
to the enclosing element.