Delete elements from an array given an array of indices


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

A rough "it works" way to delete elements from an array given the array of indices to delete. A new array is created by copying over the remaining elements.

Any suggestions on how to make this more efficient appreciated :)


Copy this code and paste it in your HTML
  1. public void deleteElementsAt(int[] rows) {
  2. if(null == rows || rows.length == 0) {
  3. return;
  4. }
  5.  
  6. int newSize = data.length - rows.length;
  7. Object[][] newData = new Object[newSize][4];
  8. int chkIndex = 0;
  9. int copyIndex = 0;
  10. for(int i = 0; i < data.length; i++) {
  11. if( chkIndex < rows.length && i == rows[chkIndex] ) {
  12. chkIndex++;
  13. } else {
  14. newData[copyIndex++] = data[i];
  15. }
  16.  
  17. }
  18.  
  19. data=newData;
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.