swap elements in array java code example
Example 1: java array swap
public static void swap(int x, int y, int[] arr) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
Example 2: array.swap java
public static final <T> void swap (T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
public static final <T> void swap (List<T> l, int i, int j) {
Collections.<T>swap(l, i, j);
}
private void test() {
String [] a = {"Hello", "Goodbye"};
swap(a, 0, 1);
System.out.println("a:"+Arrays.toString(a));
List<String> l = new ArrayList<String>(Arrays.asList(a));
swap(l, 0, 1);
System.out.println("l:"+l);
}
Example 3: array.swap java
String temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
Example 4: swap chunks of array in java
import java.util.Arrays;
int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] rotate(int[] A, int r) {
int N = A.length;
int[] left = Arrays.copyOfRange(A, 0, r);
int[] right = Arrays.copyOfRange(A, r, N);
int[] result = new int[N];
int R = N - r;
for(int i=0; i<N; ++i) {
result[i] = i<R ? right[i] : left[i-R];
}
return result;
}