Is there any predefined method for array in Java with which one can directly swap two elements ? We can use a function with or without using temporary variable, that's fine. But I want to know is there any method like Arrays.sort() for swapping?
-
what is an array supposed to swap if it contains more than 2 elements???Haifeng Zhang– Haifeng Zhang2016-08-06 04:53:20 +00:00Commented Aug 6, 2016 at 4:53
-
Collections.swap(List<?> list, int i, int j);Free-Minded– Free-Minded2016-08-06 04:54:15 +00:00Commented Aug 6, 2016 at 4:54
-
@Bhatt Will array fall under List ?Soumya Kanti Naskar– Soumya Kanti Naskar2016-08-06 04:55:14 +00:00Commented Aug 6, 2016 at 4:55
-
1Nope, and there isn't a a byte code instruction for doing this, so you're stuck with a temp var.David Ehrmann– David Ehrmann2016-08-06 04:57:54 +00:00Commented Aug 6, 2016 at 4:57
-
3The person who has downvoted this question, he must give proper reason before doing this.Soumya Kanti Naskar– Soumya Kanti Naskar2016-08-06 05:00:16 +00:00Commented Aug 6, 2016 at 5:00
2 Answers
You need to use swap method of List interface. The definition of List.swap goes like this ...
public static <E> void swap(List<E> a, int i, int j) {
E tmp = a.get(i);
a.set(i, a.get(j));
a.set(j, tmp);
}
The doc says that This is a polymorphic algorithm: It swaps two elements in any List, regardless of its implementation type.
If you are unfamiliar with java Collections ,then you first need to get yourself familiar with it.
Comments
Is there any predefined method for array in Java with which one can directly swap two elements ?
Default Java API does not have any function to swap array elements. But you can swap elements of list with Collections.swap(list, index1, index2); and you can convert array to list and perform swap and then convert list to array.
If you don't want to perform such operation you can look into some third party library which can provide such function.
You can also create your own generic function.
For example,
public class Test {
@SuppressWarnings("unchecked")
public static <T> void swap(T[] arr, int index1, int index2) {
// Need to add null check and index checks
List<T> list = Arrays.asList(arr);
Collections.swap(list, index1, index2);
arr = (T[]) list.toArray();
}
public static void main(String[] args) {
Integer[] arr = { 1, 2, 3, 4, 5 };
swap(arr, 1, 2);
System.out.println(Arrays.asList(arr));
}
}
OUTPUT
[1, 3, 2, 4, 5]
NOTES :
- Above function will not work for primitive arrays
- SuppressWarnings is added to avoid uncheck casting warning
1 Comment
arr = (T[]) list.toArray(); and in fact that statement has no effect. In your description "and then convert list to array", that's not what your code does. It directly swaps the elements of the array that is backing the list.