I've created simple code to reverse an equation, but two lines are highlighted by lint
in IntelliJ IDEA. Exact message is
Call to 'substring' is redundant
final String equation = "20+3*475-2-1*4";
final int size = equation.length();
final StringBuilder sb = new StringBuilder(size);
int right = size;
for (int i = size - 1; i > -1; i--) {
switch (equation.charAt(i)) {
case '+': case '-': case '*':
sb.append(equation.substring(i + 1, right)); // this line
sb.append(equation.charAt(i));
right = i;
}
}
if (right != 0) {
sb.append(equation.substring(0, right)); // and this line
}
I haven't ever faced with a situation when lint
highlights something without a reason. But now have no idea why these calls are redundant.
You can simplify the call to this:
sb.append(equation, i + 1, right);
This avoids an explicit intermediate string construction, allowing the implementation to copy the desired part of "equation" directly.
That's because StringBuilder append is overlaoded with a function, that also takes start and end index like substring.
So instead of using
sb.append(equation.substring(i + 1, right));
you can just use
sb.append(equation, i + 1, right);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With