Arraylist folding elements

How to swap the first and last elements of an ArrayList ? I know how to exchange array elements: setting a temporary value to store the first element, letting the first element equal the last element, and then letting the last element equal the stored first element.

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

So, for an ArrayList<String> would that be?

  String a = words.get(0); int n = words.size(); words.get(0) = words.get(n-1); words.get(n-1) = a 
+50
java arraylist
Apr 12 '13 at 5:12
source share
4 answers

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

+212
Apr 12 '13 at 5:14
source share

In Java, you cannot set a value in an ArrayList by assigning it there is a set() to call:

 String a = words.get(0); words.set(0, words.get(words.size() - 1)); words.set(words.size() - 1, a) 
+12
Apr 12 '13 at 5:18
source share

Use this. Here is an online code compilation. Take a look at http://ideone.com/MJJwtc

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

Collapses items at specified positions in a specified list. (If the specified positions are equal, calling this method leaves the list unchanged.)

Parameters: list - A list to replace items. i is the index of one element to be replaced. j is the index of another element to be exchanged.

Read the official collection documents

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

+3
Apr 12 '13 at 5:16
source share
 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; } } } 
+2
Jul 26 '14 at 6:57
source share



All Articles