Blaze
Blaze

Reputation: 9

Can´t find the mistake in this code, Comparator

I have this class that implements the comparator method in a JFrame, for some reason when u put the same name twice the program falls and print this --> StringIndexOutOfBoundsException

The code of the method:

public class OrdenarCrecienteTecnico implements Comparator<Tecnico> {

    @Override
    public int compare(Tecnico a, Tecnico b) {
        String PalabraA = a.getNombre().toUpperCase();
        String PalabraB = b.getNombre().toUpperCase();
        int i = 0;
    while(i<PalabraA.length() && i<PalabraB.length() && PalabraA.charAt(i) == PalabraB.charAt(i)){    
        i++;
    }
    return PalabraA.charAt(i) - PalabraB.charAt(i);
}

}

Upvotes: 0

Views: 31

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339472

This other Answer describes your specific problem and solution.

You seem to be working too hard. Simply let the two strings do the comparison.

public class OrdenarCrecienteTecnico implements Comparator<Tecnico> {

    @Override
    public int compare(Tecnico a, Tecnico b) {
        if( Objects.isNull( a ) || Objects.isNull( b ) ) { return -1 ; }
        return a.getNombre().compareToIgnoreCase( a.getNombre() ) ;

}

Upvotes: 0

user14644949
user14644949

Reputation: 321

This code, when faced with identical strings,

while(i<PalabraA.length() && i<PalabraB.length() && PalabraA.charAt(i) == PalabraB.charAt(i)){    
    i++;
}

will fall out of the loop with i equal to the length of the string. Then you execute this:

return PalabraA.charAt(i) - PalabraB.charAt(i);

which is guaranteed to throw an out-of-bounds exception, because valid indexes run from 0 to length-1.

Upvotes: 1

Related Questions