Posted By

Voil on 12/08/10


Tagged

array


Versions (?)

Safe `arraycopy` Method


 / Published in: Java
 

Does the same as System.arraycopy(source, copyFrom ,target, copyTo, length) but without worrying about invalid input. Example for an array of characters.

  1. public void arraycopy(char[] source, int copyFrom, char[] target, int copyTo, int length) {
  2. // Input validation
  3. if(source == null || target == null)
  4. return;
  5. if(copyFrom+length >= source.length || copyTo+length > source.length)
  6. return;
  7. // Same as: System.arraycopy(source, copyFrom, target, copyTo, length);
  8. for(int i=0;i<length;i++) {
  9. target[copyTo+i] = source[copyFrom+i];
  10. }
  11. }

Report this snippet  

You need to login to post a comment.