需要对解释如何code处理ArrayList的价值观 [英] Need explanations on how this code processes Arraylist values

查看:165
本文介绍了需要对解释如何code处理ArrayList的价值观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的值,解决了此方法的输出。看在它之后,我是pretty肯定这code将重新定位在列表的前面的一对较小的值。我使用的值的ArrayList [2,6,1,8] 输入,结果是 [1,2,6,8] ,这是如我所料。但对于 [30,20,10,60,50,40] 它产生 [10,30,40,20,60,50] 时,我期望 [40,50,10,20,30,60] 。因此,任何人都可以请向我解释这code实际上是如何处理的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!

推荐答案

下面是一步情况,步:


  • 您的列表的初始状态:[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]

这篇关于需要对解释如何code处理ArrayList的价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆