DerMike
DerMike

Reputation: 16190

When and why should I use System.arraycopy (or: arrays vs collections)

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

Answers (5)

user3011731
user3011731

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

Joe23
Joe23

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

bruno conde
bruno conde

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

Michael Borgwardt
Michael Borgwardt

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

  • More code
  • Thus, more likely to contain an error
  • In most cases slower because System.arraycopy(...) is a native method that can use fast memory copy routines provided by the OS.

Upvotes: 4

Bombe
Bombe

Reputation: 83928

Arrays are not Collections. 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

Related Questions