Results 1 to 3 of 3
  1. #1
    nalinda is offline Member
    Join Date
    Nov 2007
    Posts
    7
    Rep Power
    0

    Default deleting elements

    how do i delete an element from an array? Give me the simplest way. And how do i do it without leaving gaps in the array?

  2. #2
    staykovmarin is offline Senior Member
    Join Date
    Nov 2007
    Location
    Newport, WA
    Posts
    141
    Rep Power
    0

    Default

    You cant, Arrays are a set size, you can set the contents to null, but then you will be left with "gaps".

    Use HashMap, ArrayList, or one of the million other collection classes.

  3. #3
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Here's a couple of simple ways.
    Java 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.

Similar Threads

  1. Deleting All rows in the JTable
    By surot in forum New To Java
    Replies: 1
    Last Post: 04-16-2008, 10:44 AM
  2. Deleting a File that is opened
    By ravian in forum Advanced Java
    Replies: 6
    Last Post: 01-30-2008, 02:05 PM
  3. Deleting files after filtering the extensions
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-25-2008, 07:00 PM
  4. Deleting an empty directory
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-13-2008, 07:17 AM
  5. Deleting certain image pixels..
    By Brightside in forum New To Java
    Replies: 1
    Last Post: 05-22-2007, 09:21 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •