有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将comparator与arraylist结合使用

我有一个练习,以升序输出用户输入的所有字符串
当用户输入“quit”时,程序应该停止

   import java.util.Scanner;
   import java.util.ArrayList;
   import java.util.Comparator;
   import java.util.Collections;
   public class Exercise2{
        public static void main (String[] args) {
        ArrayList<String> list=new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        String word="string";
        while(!word.equals("quit")){            // cycle will continue till string will contain a word "quit".
             System.out.println("Please enter a string line. String can be whatever you want. After you enter a string please press Enter");
        word=scanner.nextLine();
        if(word.equals("quit"))
        break;
        list.add(word);
        }
        Collections.sort(list, new Comparator<String>(){
        public int compare(String o1, String o2){
                if(o1.length()>o2.length()){
                     return 1;
            }else{
                    return o1.compareTo(o2);
                }
    }

});

    System.out.println(list);
}
}

有人能解释一下为什么我的代码不起作用吗
我想用比较仪来做


共 (1) 个答案

  1. # 1 楼答案

    您的比较方违反了compare的合同,该合同规定;b然后b<;a也一定是真的。然而,如果你通过“a1”和“b”,你会得到1,而如果你通过“b”和“a1”,你不会得到-1,但也会得到1

    摘自JavaDoc:

    The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y.

    你需要保持一致,也就是说,如果你想先比较长度,那么你需要这样做,并且只在长度相等时使用自然顺序:

     public int compare(String o1, String o2){
       //for Java 6 and below you could just do o1.length() - o2.length() 
       //as the return value doesn't have to be -1 or 1 but negative, 0 or positive
       int result = Integer.compare( o1.length(), o2.length() ); /
       if( result == 0 ) {
         result = o1.compareTo(o2);
       }
       return result;
     }