![](/img/trans.png)
[英]make a sort of two ArrayList if an element change a position the second one of the other arraylist change also the position
[英]element position in arraylist after sort
假设我有以下内容:
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
等等。这将为您提供记录原始位置索引的元组列表。
您可以使用HashMap
Map<Integer, Double> test = new Hashmap<>();
test.put(1, 1.0);
test.put(2, 1.3); //etc.
即使您对其进行排序,键也不会改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.