数组列表交换元素

如何交换 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
160574 次浏览

You can use Collections.swap(List<?> list, int i, int j);

Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc

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

Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.

Read The official Docs of collection

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);


}
}

Oneline compilation example http://ideone.com/MJJwtc

In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:

String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
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;
}
}
}