【问题标题】:Finding the string that is first in alphabetical order in an ArrayList of Strings在字符串的 ArrayList 中查找按字母顺序排在第一位的字符串
【发布时间】:2016-03-12 00:10:00
【问题描述】:

我有一个字符串形式的笔记 ArrayList(一个例子是“取出垃圾”。我有一个笔记类,其中一种方法应该通过存储在 ArrayList 中的笔记和找到字母表中排在第一位的那个。这是我目前的方法:

public String firstAlphabetically() {
        String min = "";
        for (int i = 0; i < notes.size(); i++) {
            for (int j = i + 1; j < notes.size() + 1; i++) {
                if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
                    min = notes.get(i);
                } else {
                    min = notes.get(j);
                }
            }
        }
        return min;
    }

但是,当我运行该程序时,我在此行收到了一个越​​界错误:for (int j = i + 1; j &lt; notes.size() + 1; i++)。我知道什么是越界错误,但我不知道该行的哪一部分会导致程序崩溃。谁能告诉我我做错了什么?

【问题讨论】:

  • notes.size() + 1 -> notes.size()
  • 当 i = notes.size()-1 时 j 是 notes.size(),当在 if 语句中执行 notes.get(j) 时会抛出 IndexOutOfBoundsException
  • 您也可以使用:Collections.sort(notes); 并获取第一个。
  • 如果您不介意数组被重新排序:Collections.sort(notes); return notes.get(0);
  • @Siguza 谢谢,成功了!

标签: java arrays arraylist intellij-idea alphabetical


【解决方案1】:

问题 1:
循环终止条件应该是i &lt; notes.size()

问题 2:
代码太多。试试这个 1-liner:

return notes.stream().sorted().findFirst().orElse(null);

【讨论】:

    【解决方案2】:

    添加:

    implements Comparable<Note>
    

    到你的类签名,然后在你的 Note 类中实现 comparTo() 方法。然后你可以使用:

    Collections.sort(listOfNotes)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2021-08-29
      • 2014-11-26
      • 2012-01-31
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2019-04-17
      相关资源
      最近更新 更多