View Single Post
  #3 (permalink)  
Old 12-06-2007, 03:42 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Here's a couple of simple ways.
Code:
public static void main(String[] args) { String[] items = { "cat", "dog", "horse", "fish", "cow" }; System.out.println("items = " + Arrays.toString(items)); items = removeItemAt(2, items); System.out.println("items = " + Arrays.toString(items)); items = remove(3, items); System.out.println("items = " + Arrays.toString(items)); } private static String[] removeItemAt(int index, String[] array) { String[] retVal = new String[array.length-1]; for(int j = 0, k = 0; j < array.length; j++) { if(j == index) continue; retVal[k++] = array[j]; } return retVal; } private static String[] remove(int index, String[] array) { int len = array.length; String[] retVal = new String[len-1]; System.arraycopy(array, 0, retVal, 0, index); System.arraycopy(array, index+1, retVal, index, len-index-1); return retVal; }
staykovmarin's way using collections is even easier. The designers say that collections run faster than arrays. One advantage of using arrays is that you don't have to deal with generics.
Reply With Quote