88

如何交换 an 的第一个和最后一个元素ArrayList?我知道如何交换数组的元素:设置一个临时值来存储第一个元素,让第一个元素等于最后一个元素,然后让最后一个元素等于存储的第一个元素。

int a = values[0];
int n = values.length;
values[0] = values[n-1];
values[n-1] = a;

那么对于一个ArrayList<String>会是这样的吗?

String a = words.get(0);
int n = words.size();
words.get(0) = words.get(n-1);
words.get(n-1) = a
4

4 回答 4

287

您可以使用Collections.swap(List<?> list, int i, int j);

于 2013-04-12T05:14:56.923 回答
16

在Java中,您不能通过分配给它来设置ArrayList中的值,有一个set()方法可以调用:

String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
于 2013-04-12T05:18:14.940 回答
13

像这样使用。这是代码的在线编译。看看http://ideone.com/MJJwtc

public static void swap(List list,
                        int i,
                        int j)

交换指定列表中指定位置的元素。(如果指定的位置相等,则调用此方法会使列表保持不变。)

参数: list - 交换元素的列表。i - 要交换的一个元素的索引。j - 要交换的另一个元素的索引。

阅读收集的官方文档

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29

import java.util.*;
import java.lang.*;

class Main {
    public static void main(String[] args) throws java.lang.Exception       
    {    
        //create an ArrayList object
        ArrayList words = new ArrayList();

        //Add elements to Arraylist
        words.add("A");
        words.add("B");
        words.add("C");
        words.add("D");
        words.add("E");

        System.out.println("Before swaping, ArrayList contains : " + words);

        /*
      To swap elements of Java ArrayList use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.

      If the specified positions are equal, list remains unchanged.

      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.        */

        Collections.swap(words, 0, words.size() - 1);

        System.out.println("After swaping, ArrayList contains : " + words);    

    }
}

在线编译示例http://ideone.com/MJJwtc

于 2013-04-12T05:16:32.167 回答
2
for (int i = 0; i < list.size(); i++) {
        if (i < list.size() - 1) {
            if (list.get(i) > list.get(i + 1)) {
                int j = list.get(i);
                list.remove(i);
                list.add(i, list.get(i));
                list.remove(i + 1);
                list.add(j);
                i = -1;
            }
        }
    }
于 2014-07-26T06:57:55.100 回答