假设我有以下内容:
List<Double> test = new ArrayList<Double>();
test.add(1.0);
test.add(1.3);
test.add(1.1);
test.add(1.2);
test.add(1.5);
如果我想对值进行排序,我可以使用Collections.sort(test)
。这将按升序对它们进行排序。有没有办法在排序发生之前仍然保留对原始位置的引用?
例如排序后将是
test.add(1.0);
test.add(1.1); - would be index position 3
test.add(1.2); - would be index position 2
test.add(1.3);
test.add(1.5);
这是可能的还是只是一种错误的方法?
最佳答案
因为 Collections.sort()
对原始列表进行排序并且不给您副本,所以不会。在排序之前,您必须获取列表的副本。
另一种方法是创建一个元组列表 - 原始值及其索引,并使用比较器单独比较值进行排序,例如
test.add(new Pair(1, 1.0));
test.add(new Pair(2, 1.2));
Collections.sort(test, new PairComparator()); // this sorts on the 2nd value of each Pair
等等。这将为您提供一个记录了原始位置索引的元组列表。
关于java - 排序后数组列表中元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23930221/