在Java中,是否有预定义的方法可以直接交换两个数组元素?我们可以使用带有或不带临时变量的函数来实现这一点,但我想知道是否有像Arrays.sort()这样的交换方法?
在Java中,是否有预定义的方法可以直接交换两个数组元素?我们可以使用带有或不带临时变量的函数来实现这一点,但我想知道是否有像Arrays.sort()这样的交换方法?
List
接口的swap
方法。 List.swap
的定义如下...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);
}
这份文档说明了:这是一个多态算法:它可以交换任何类型的List中两个元素,不论其具体实现方式。
如果您不熟悉java集合
,那么您首先需要熟悉一下。
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));
}
}
输出
[1, 3, 2, 4, 5]
注意:
arr = (T[]) list.toArray()
,实际上该语句没有任何效果。在您的描述中,“然后将列表转换为数组”,这并不是您的代码所做的。它直接交换支持列表的数组的元素。 - DodgyCodeException