int temp = name.get(0);
name.set(0, name.get(1));
name.set(1, temp)
Collections.swap(name, 0, 1)
I want to swap two elements and don't know which is more efficient. It seems like the runtime of both swaps are the same but I'm not too sure. Thanks!
I want to swap two elements and don't know which is more efficient. It seems like the runtime of both swaps are the same but I'm not too sure.
The only way to be sure is to write a proper micro-benchmark, run it (on a number of hardware platforms / Java versions) and interpret the results.
We can look at the source code, and make some informed guesses, but we cannot deduce micro-level efficiency from first principles1.
My advice:
1 - ... unless there is someone here with an unhealthily detailed amount of knowledge in their heads about how real world Java JIT compilers actually work across multiple platforms. And if there is someone here like that, we should probably just let them rest quietly, rather than bugging them with questions like this :-)