Reputation: 1181
package mediumchallenge;
import java.util.Arrays;
import java.util.Comparator;
public class sortarrayofstringsbylength{
private static class comparelengths implements Comparator<String>{
@Override
public int compare(String arg0, String arg1) {
// TODO Auto-generated method stub
return (arg0.length()- arg1.length());
}
}
private static class lastchar implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
// TODO Auto-generated method stub
return (s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1));
}
}
public static void main(String args[]){
String arr[] = {"abd" , "abc","y" , "rtyuodfdjfhd","weq","wge",""};
Arrays.sort(arr);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
// sorts according to length of string
Arrays.sort(arr, new comparelengths());
for(int j=0;j<arr.length;j++){
System.out.println(arr[j]);
}
//sorts lexicographically according to last letter
Arrays.sort(arr, new lastchar());
for(int k=0;k<arr.length;k++){
System.out.println(arr[k]);
}
}
}
I'm trying to sort the string array based on last character of each string using comparator. It's giving me String index out of range -1 exception
Upvotes: 0
Views: 1134
Reputation: 1
String arr[] = {"abd" , "abc","y" , "rtyuodfdjfhd","weq","wge",""};
The last element is "", it's length is zero. The code "s1.charAt(s1.length()-1)" will throw String index out of range -1 exception.
Upvotes: 0
Reputation: 26279
A solution would be to check the lengths themselves for zero.
s2
is empty and s1
is not empty, s2
should go behind s1
so we return -1
.s1
is empty and s2
is not empty, s1
should go behind s2
so we return 1
.s2
is empty and s1
is empty, they are equal
and we should return 0
.Below an example of such an implementation:
@Override
public int compare(String s1, String s2) {
// Returns a negative integer, zero, or a positive integer
// as the first argument is less than, equal to, or greater than the second.
if(s1.length() == 0 && s2.length() > 0)return 1;
if(s2.length() == 0 && s1.length() > 0)return -1;
if(s2.length() == 0 && s1.length() == 0)return 0;
return (s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1));
}
Basically you need to decide if you will allow empty strings and what action to take when they are encountered (e.g. push them below).
If you want empty strings to be first use:
if(s1.length() == 0 && s2.length() > 0)return -1;
if(s2.length() == 0 && s1.length() > 0)return 1;
if(s2.length() == 0 && s1.length() == 0)return 0;
If you want empty strings to be last use:
if(s1.length() == 0 && s2.length() > 0)return 1;
if(s2.length() == 0 && s1.length() > 0)return -1;
if(s2.length() == 0 && s1.length() == 0)return 0;
Upvotes: 1