Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
[;-)

like image 642
DerMike Avatar asked Nov 22 '25 08:11

DerMike


2 Answers

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.
like image 134
Michael Borgwardt Avatar answered Nov 23 '25 21:11

Michael Borgwardt


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().

like image 28
Bombe Avatar answered Nov 23 '25 20:11

Bombe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!