ArrayList元素交换:Collections.swap()与临时变量法哪个效率更高?
Collections.swap()? Great question! Let’s dig into this to figure out which approach is better, both in terms of efficiency and practicality.
First, Let’s Look at the Underlying Implementations
Let’s start with what each approach actually does under the hood:
Manual Swap
Your manual approach looks like this:
int temp = name.get(0); name.set(0, name.get(1)); name.set(1, temp);
This involves two explicit get() calls (to fetch both elements) and two set() calls (to overwrite each index with the new value).
Collections.swap()
The standard library’s Collections.swap() method (simplified from OpenJDK source) uses a smarter one-liner:
public static void swap(List<?> list, int i, int j) { final List l = list; l.set(i, l.set(j, l.get(i))); }
Here, it leverages the fact that List.set() returns the old value at the index. So it:
- Fetches the element at index
i - Sets index
jto that element, capturing the old value ofjin the process - Sets index
ito the captured old value ofj
Efficiency Breakdown
Let’s count the underlying array operations (since ArrayList uses an array internally):
- Manual swap: 2
get()calls (each reads one array element) + 2set()calls (each reads the old element and writes the new one) = 6 total array operations. - Collections.swap: 1
get()call + 2set()calls (each with a read and write) = 5 total array operations.
Technically, Collections.swap() saves one array read operation. But here’s the key point: this difference is negligible for almost all real-world scenarios. The JVM optimizes these low-level operations heavily, and unless you’re swapping elements millions of times in a tight loop, you’ll never notice a performance gap.
Practicality and Readability
Where Collections.swap() truly stands out is in code quality:
- Conciseness: It’s a single line that immediately communicates your intent, whereas the manual approach requires three lines that force readers to parse the swap logic.
- Type safety: For generic ArrayLists (e.g.,
ArrayList<String>), the manual approach requires you to handle the temp variable’s type correctly.Collections.swap()handles generics seamlessly, eliminating the risk of type errors. - Flexibility: It works with any
Listimplementation (LinkedList, Vector, etc.), not just ArrayList. If you ever switch your list type later, you won’t have to rewrite the swap logic. - Proven reliability: This is a well-tested standard library method used by millions of developers. You don’t have to worry about off-by-one errors or other bugs that could creep into manual swap code.
Final Recommendation
If you’re chasing absolute micro-optimization for a performance-critical loop, Collections.swap() is slightly more efficient. But for 99% of cases, prioritize Collections.swap() for its readability, safety, and flexibility. The tiny performance difference is not worth sacrificing clean, maintainable code.
内容的提问来源于stack exchange,提问作者daswagarv

