Reputation: 16190
In the answers here lately, I found some different habits (or flavours). So I wonder when and why is the use of Java's System.arraycopy(...)
preferable to something like Collection.addAll(...)
? When not?
Edit: It boils down to arrays vs. collections. Thanks so far. But which can be handled more effeciently by the computer or is... well... better for programmers?
Thanks
Mike
[;-)
Upvotes: 2
Views: 3312
Reputation: 85
Array are not collection. that's why we are using Sysytem.arrcopy its native method for copying array but it is very fast
Upvotes: 0
Reputation: 5782
IMHO I would recommend the usage of collections in most cases. Especially in interfaces and public methods.
For example if you can choose between:
public List<Integer> getFoo();
public int[] getFoo();
The first method gives you the opportunity to change the implementation ArrayList
vs LinkedList
, etc. Or to return an immutable version via Collections.unmodifiableList()
.
If you return an array in an interface method you might be forced to make a defensive copy before returning it, since you cannot prevent the client from changing the array content. Furthermore lists have only few disadvantages compared to arrays, you can almost always replace an array with an ArrayList
for example.
Place where arrays still make sense would be varargs methods, or algorithmic code, where the speed benefit of operations like clone
and System.arraycopy
are relevant.
Upvotes: 1
Reputation: 48265
You comparison doesn't make many sense ... Arrays are not Collections. System.arraycopy
is a very fast native
method for copying arrays. That's why people and the Java framework itself use it.
Upvotes: 2
Reputation: 346377
Well, for one thing System.arraycopy(...)
works on arrays, and Collection.addAll()
on collections - so what you can use depends on what kind of objects you have to work with.
The alternative to System.arraycopy(...)
with arrays is writing a loop and copying elements manually. This is
System.arraycopy(...)
is a native method that can use fast memory copy routines provided by the OS.Upvotes: 4
Reputation: 83928
Arrays are not Collection
s. So whenever you need to copy things from an array to another array, use System.arraycopy
. If you need to add things from one Collection
to another Collection
, use Collection.add()
or Collection.addAll()
.
Upvotes: 2