gpt4 book ai didi

java - ArrayList 排序元素的初始索引

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:30 24 4
gpt4 key购买 nike

以下代码实现了nfit的升序排序。

public static void main(String[] args) {
ArrayList<Double> nfit = new ArrayList<Double>();

nfit.add(2.0);
nfit.add(5.0);
nfit.add(1.0);
nfit.add(8.0);
nfit.add(3.0);

// Sort individuals in ascending order
Collections.sort(nfit);

System.out.print(nfit);

}

输出是:

[1.0, 2.0, 3.0, 5.0, 8.0]

我的问题是如何获取已排序元素的初始索引?在此示例中,我的问题的答案如下:

[2, 0, 4, 1, 3]

如何获取这些索引?

最佳答案

复制 ArrayList 并排序,然后使用 indexOf。

ArrayList<Double> nfit = new ArrayList<Double>();
nfit.add(2.0);
nfit.add(5.0);
nfit.add(1.0);
nfit.add(8.0);
nfit.add(3.0);
ArrayList<Double> nstore = new ArrayList<Double>(nfit); // may need to be new ArrayList(nfit)
Collections.sort(nfit);
int[] indexes = new int[nfit.size()];
for (int n = 0; n < nfit.size(); n++){
indexes[n] = nstore.indexOf(nfit.get(n));
}
System.out.println(Arrays.toString(indexes));

如果你想要 ArrayList 中的索引,

Collections.sort(nstore);
for (int n = 0; n < nfit.size(); n++){
nstore.add(n, nfit.indexOf(nstore.remove(n)));
}
Collections.sort(nfit);

这将导致一个排序的 ArrayList nfit 和一个索引的 ArrayList nstore。

编辑:在for循环中

for (int n = 0; n < nfit.size(); nfit++){
nstore.add(n, nfit.indexOf(nstore.remove(n)));
}

循环计数必须在 n 上迭代,而不是在 nfit 上迭代找到更正后的代码:

for (int n = 0; n < nfit.size(); n++){
nstore.add(n, nfit.indexOf(nstore.remove(n)));
}

关于java - ArrayList 排序元素的初始索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com