ArrayList 已排序元素的初始索引

Kla*_*sos 5 java sorting collections arraylist

下面的代码实现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);

}
Run Code Online (Sandbox Code Playgroud)

输出是:

[1.0, 2.0, 3.0, 5.0, 8.0]
Run Code Online (Sandbox Code Playgroud)

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

[2, 0, 4, 1, 3]
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到这些索引?

Jus*_*tin 4

复制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));
Run Code Online (Sandbox Code Playgroud)

如果你想要 ArrayList 中的索引,

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

这将产生一个已排序的 ArrayList nfit 和一个索引的 ArrayList nstore。

编辑:在for循环中

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

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

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