Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to 'substring' is redundant

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.

like image 454
Maxim Avatar asked Sep 28 '18 16:09

Maxim


2 Answers

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.

like image 182
Stefan Haustein Avatar answered Sep 29 '22 18:09

Stefan Haustein


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); 
like image 39
Axel M Avatar answered Sep 29 '22 16:09

Axel M