Safe `arraycopy` Method


/ Published in: Java
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.