Java中是否有任何预定义的数组方法可以用来直接交换两个元素?我们可以使用带有或不带有临时变量的函数,这很好。但是我想知道是否有像Arrays.sort()这样的交换方法?
Java中是否有任何预定义的数组方法可以用来直接交换两个元素?
默认的Java API没有任何交换数组元素的功能。但是您可以使用交换list的元素,Collections.swap(list, index1, index2);
并且可以将array转换为list并执行交换,然后将list转换为array。
如果您不想执行此类操作,则可以查看一些可以提供此类功能的第三方库。
您也可以创建自己的通用函数。
例如,
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]
注意事项:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句