在Java中有效地交换数组元素 [英] Effective swapping of elements of an array in Java
问题描述
我想知道是否有更有效的方式在数组中交换两个元素,而不是这样做:
I am wondering if there is a more efficient way of swapping two elements in an Array, than doing something like this:
String temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
嗯,这显然不坏甚至错,但我需要经常换掉所以我是有兴趣,如果有任何Libs或其他东西提供更有效的方法吗?
Well, this is obviously not bad or even wrong, but I need to swap very often so I am interested if there are any Libs or something that provide a more efficient way to do this?
推荐答案
不。您可以使用一个函数使每个使用它的地方更简洁,但最后,完成的工作将是相同的(加上函数调用的开销,直到/除非HotSpot将其内联移动—以帮助它使用它,使功能静态最终
)。
Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the functon static final
).
这篇关于在Java中有效地交换数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!