【问题标题】:How do I print the indices of the three greatest numbers in an ArrayList?如何打印 ArrayList 中三个最大数字的索引?
【发布时间】:2016-08-12 15:31:32
【问题描述】:

这里,tvalue 是我的 ArrayList。我的 ArrayList 中有 10 个数字,从 110。我想在排序后打印 ArrayList 中最后三个数字的索引以检索列表中的三个最大数字。但是,结果我得到了不合适的值。谁能帮我吗?下面是一些与我的程序相关的示例代码,

        Collections.sort(tvalue);
        System.out.println(tvalue.get(tvalue.size()-1));
        System.out.println(tvalue.get(tvalue.size()-2));
        System.out.println(tvalue.get(tvalue.size()-3));

我无法使用此代码获取索引, int index=tvalue.indexOf(tvalue.get(tvalue.size()-1)); System.out.println(index);

【问题讨论】:

  • 你遇到了什么错误??
  • 你得到了什么输出?
  • 您已经对值进行了排序,因此您只是将值取回。创建一个全新的ArrayList 然后排序。
  • 那么 `int index= initialList.indexOf(tvalue.get(tvalue.size()-1)); `
  • 我得到了不合适的索引值

标签: java sorting arraylist


【解决方案1】:

只是将上面的解释放入代码中:

List sortedValue = new ArrayList<>(tvalue);
Collections.sort(sortedValue);
for (int i=1; i<4; i++) {
    System.out.println(tvalue.indexOf(tvalue.get(sortedValue.size() - i)));
}

【讨论】:

    【解决方案2】:

    由于您已经对列表进行了排序,indexOf 方法不起作用。您需要创建一个初始 ArrayList(或 List)对象,然后按值复制所有内容。然后,像上面那样对其进行排序,然后执行 int index = initialList.indexOf(____)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2012-02-17
      • 2019-05-14
      • 2021-02-16
      相关资源
      最近更新 更多