Call to 'substring' is redundant

Maxim :

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.

Stefan Haustein :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72520&siteId=1