首页 > 解决方案 > 我收到一条错误消息,提示“String 类型的方法 compare(String, String) 未定义”为什么我不能对二维数组进行排序?

问题描述

我正在开发一个危险的 GUI 游戏,我在其中对我的二维问题进行排序。我返回的 .compare 行出现错误。错误说“方法比较(字符串,字符串)未定义字符串类型”

       JButton btnSort = new JButton("Sort");
            btnSort.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                 String[][] questions = new String[][] { {"How many continents are there?"}, {"What is the capital of Canada?"}, {"What is the largest country in the world?"}, {"What is the largest ocean in the world?"}, {"How many oceans are there in the world?"}, {"How many countries make up Africa?"}, {"How many countries in the world begin with the word United?"}, {"Where is Milan?"}, {"What is the least populated US state?"}, {"What is the capital of Australia?"}, {"How many countries begin with the letter J?"}, {"Which country has the most lakes in the world?"}};


                            java.util.Arrays.sort(questions, new java.util.Comparator<String[]>() {
                                public int compare(String[] a, String[] b) {
                                    return String.compare(a[0], b[0]);
                                }
                            });

                }
            });

标签: javastringsortingcomparator

解决方案


因为String.compareTo(String)不是采用两个参数的方法(并且没有命名为compare)。它是一种实例方法,可以将一个实例与另一个实例进行比较;喜欢,staticString

java.util.Arrays.sort(questions, new java.util.Comparator<String[]>() {
    public int compare(String[] a, String[] b) {
        return a[0].compareTo(b[0]);
    }
});

推荐阅读