需要解释此代码如何处理 Arraylist 值 [英] Need explanations on how this code processes Arraylist values
问题描述
public static void mystery1(ArrayList<Integer> list) {
for (int i = list.size() - 1; i > 0; i--) {
if (list.get(i) < list.get(i - 1)) {
int element = list.get(i);
list.remove(i);
list.add(0, element);
}
}
System.out.println(list);
}
我正在尝试使用给定的 ArrayList 值
集来解决此方法的输出问题.在查看它之后,我很确定这段代码会将一对的较小值重新定位在列表的前面.我使用值 [2, 6, 1, 8]
的 ArrayList 进行输入,结果是 [1, 2, 6, 8]
,正如我所料.但是对于 [30, 20, 10, 60, 50, 40]
它产生了 [10, 30, 40, 20, 60, 50]
当我期望 [40,50,10,20,30,60]
.因此,任何人都可以向我解释这段代码实际上是如何处理 Arraylist
的吗?谢谢!
I'm trying to solve the for the output of this method with given sets of ArrayList values
. After looking over it, I was pretty sure this code would relocate the smaller value of a pair in the front of the list. I used an ArrayList of values [2, 6, 1, 8]
for input and the result was [1, 2, 6, 8]
, which was as I expected. But for [30, 20, 10, 60, 50, 40]
it produced [10, 30, 40, 20, 60, 50]
when I expected [40,50,10,20,30,60]
. Therefore can anyone please explain to me how this code actually processes the Arraylist
? Thanks!
推荐答案
这是发生的事情,一步一步:
Here is what happens, step by step:
- 列表的初始状态:[30, 20, 10, 60, 50, 40]
- 是 40 <50?是的.所以去掉40,把它作为列表的第一个元素:[40, 30, 20, 10, 60, 50]
- 是 60 <10?不.不要碰任何东西:[40, 30, 20, 10, 60, 50]
- 是 10 <20?是的.所以去掉10,把它作为列表的第一个元素:[10, 40, 30, 20, 60, 50]
- 是 30 <40?是的.所以去掉30,把它作为列表的第一个元素:[30, 10, 40, 20, 60, 50]
- 是 10<30?是的.所以删除 10,并将其作为列表的第一个元素:[10, 30, 40, 20, 60, 50].
结果是:[10, 30, 40, 20, 60, 50]
The result is then: [10, 30, 40, 20, 60, 50]
这篇关于需要解释此代码如何处理 Arraylist 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!