用于字符串数组的Java比较器不起作用

时间:2014-05-05 16:34:04

标签: comparator

我已经复制了我的代码,所以你可以看到我想要做的事情。第一部分在我尝试排序之前工作正常,我只是希望它输出从长度到长度的城市,因为第一部分输出正常而且我很困难,真的很感激一些帮助。

public class Q3 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
     String strCity[] = new String[3]; //declaring array of three Irish Cities
     //adding elements to the array
     strCity[0] ="Cork";

     strCity[1] ="Dublin";

     strCity[2] ="Waterford";

     //declaring the shortest to longest in the array before sorting
     System.out.println("This is the list before sorting:");
     for (int i=0;i<strCity.length;i++){

              System.out.println(strCity[i]);

     }
}
}

class comp implements Comparator<String> {
  public int compare(String o1, String o2)
  {
  System.out.println("This is the sorted list:");
      if (o1.length() > o2.length()) {
      return 1;
    } else if (o1.length() < o2.length()) {
      return -1;
    } else {
      return 0;
}

1 个答案:

答案 0 :(得分:0)

喜欢

public class Sort {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String strCity[] = new String[3]; //declaring array of three Irish Cities
        //adding elements to the array
        strCity[0] = "Cork";

        strCity[1] = "Dublin";

        strCity[2] = "W ";

        //declaring the shortest to longest in the array before sorting
        System.out.println("This is the list before sorting:");
        for (int i = 0; i < strCity.length; i++) {

            System.out.println(strCity[i]);

        }
        Arrays.sort(strCity, new LengthComparator());
        System.out.println(Arrays.toString(strCity));
    }

    static class LengthComparator implements Comparator<String> {
        public int compare(String o1, String o2) {
            if (o1.length() > o2.length()) {
                return 1;
            } else if (o1.length() < o2.length()) {
                return -1;
            } else {
                return 0;
            }
        }
    }
}
  • 从Comparator中删除打印方法。比较通过排序算法执行的每个比较的方法调用。