交换ArrayList中的项目

时间:2017-09-19 01:59:03

标签: java

我试图创建一个在ArrayList中交换两个项的方法。作为一个例子,我试图让它成为oneList = [" dog"," cat"," mouse"," panda&# 34;]然后你交换(1,2,oneList)它将最终成为["狗","鼠标"," cat",&# 34;熊猫"]

void swap(int a, int b, ArrayList<String> oneList)
{
    oneList.set(a, oneList.get(b)) //puts whatever is in position b into position a
}

3 个答案:

答案 0 :(得分:3)

您可以使用以下方式更改:

String temp = oneList.get(a); 
oneList.set(a, oneList.get(b));
oneList.set(b,temp);

或使用Collections内置swap方法

void swap(int a, int b, ArrayList<String> oneList) {
    // do some bounds check
    Collections.swap(oneList, a, b);
}

答案 1 :(得分:1)

使用临时变量使交换成为可能:

void swap(int a, int b, ArrayList<String> oneList) {
    // you might also want to check that both a and b fall within the bounds of the list
    String temp = oneList.get(b);
    oneList.set(b, oneList.get(a));
    oneList.set(a, temp);
}

答案 2 :(得分:1)

正如其他答案所指出的那样,您只更新列表中的第一个值(您需要先保存它,然后再设置第二个值)。此外,您可以在任何类型的List上使该方法通用(请编程到界面)。像,

<T> void swap(int a, int b, List<T> oneList) {
    T t = oneList.get(a);
    oneList.set(a, oneList.get(b));
    oneList.set(b, t);
}