【问题标题】:I get an error saying "The method compare(String, String) is undefined for the type String" Why can't I sort my 2D array? [closed]我收到一条错误消息,提示“String 类型的方法 compare(String, String) 未定义”为什么我不能对二维数组进行排序? [关闭]
【发布时间】:2020-04-22 13:53:21
【问题描述】:

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

       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]);
                                }
                            });

                }
            });

【问题讨论】:

  • 为什么你认为String 有一个compare 方法? 文档,即String 的javadoc 没有显示这种方法。使用return a[0].compareTo(b[0]);
  • arraysuser-interface 的相关性让我无法理解。

标签: java string sorting comparator


【解决方案1】:

因为String.compareTo(String) 不是采用两个参数的static 方法(未命名比较)。这是一种实例方法,可以将一个String 实例与另一个实例进行比较;喜欢,

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

【讨论】:

    【解决方案2】:

    这是因为您将比较方法用作静态方法。像任何其他实例方法一样使用它。你甚至可以使用 compareTo()。

    【讨论】:

    • String.compare() 不存在,无论是作为静态方法还是实例方法。
    • 我并不是说将它用作字符串类的 compare() 方法,因为它不存在。我所说的是使用 compare() 作为比较器类的实例方法。此外,我们还可以使用可比较类的 compareTo()。
    猜你喜欢
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多