-1

Let's say I have a String array with multiple items in it

String[] dog = {"doggy","doggo","BigDog","dawgg"};

How do I remove "doggo" from the string array?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
TheHay
  • 21
  • 4
  • 1
    Spoiler: You have to create another array. – Spectric Sep 24 '20 at 21:14
  • 4
    Does this answer your question? [How do I remove objects from an array in Java?](https://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) – Svirin Sep 24 '20 at 21:16
  • "Remove" here is unclear. Do you want to resize the array? Is having a `null` element in the array acceptable? And why not just use an `ArrayList` instead, which actually does resize itself. – markspace Sep 24 '20 at 21:23
  • I want to completely remove /delete "doggo" from the array, like it was never there. The array would look like this if "doggo" was removed:>>>>>>String[] dog = {"doggy","BigDog","dawgg"}; – TheHay Sep 24 '20 at 21:25
  • Then I think Svirin's link is the best bet. – markspace Sep 24 '20 at 21:27

3 Answers3

0

Arrays are immutable - the size of an array cannot be changed once it is made, nor can items be "added".

However, I wrote a method which can remove items in an array for you:

    public class RemoveArrayItem {
        public static void main(String[] args) {
            String[] array = {"foo", "bar", "bar"};
            String[] newarray = removeArrayItem(array, "bar");
            for(int i = 0; i < newarray.length; i++) {
                System.out.print(array[i]+" ");
            }
            
        }
        public static String[] removeArrayItem(String[] array, String item) {
            
            boolean doescontain = false;
            for(int i = 0; i < array.length; i++) {
                if(array[i].equals(item)) {
                    doescontain=true;
                }
            }
            if(doescontain) {
                int newindex = 0;
                String[] newarray = new String[array.length-1];
                for(int i = 0; i < array.length; i++) {
                    if(!array[i].equals(item)) {
                        newarray[newindex]=array[i];
                        newindex++;
                    }
                }
                return newarray;
    
            }else {
                return array;
            }
    
            
        

}
}

Test Case: (array)

foo, bar

Output

foo

Test Case 2

foo bar bar

Output

foo bar

(When I set the method's item to "bar")

Explanation:

The method receives 2 parameters, an array (String) and the item (String) that you want to remove.

First off, it loops through the array to check whether it contains the desired item. If it doesn't, it directly returns the original array.

If it does, then it will create a new array and start looping through the original array. If the current item of the array in the for loop is not equal to the item, it assigns that variable to a position in a new array (newarray). If it does, then it will do nothing.

Then it will return newarray.

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • This code has a potential bug (although the OP's request is unclear). If the array contains `{"foo","bar","foo","bar"}` and is requested to remove `"bar"`, what happens? – markspace Sep 24 '20 at 21:29
  • @markspace Eye of an eagle! Thanks. I've fixed it. **EDIT:** hold on there's a bug. – Spectric Sep 24 '20 at 21:33
  • 1
    Strictly speaking, arrays are not immutable as their elements could be modified or swapped around and the only fixed property is array size. – MartinBG Sep 24 '20 at 21:39
0

I believe the most succinct way to do this with recent versions of Java (>= 8) is:

import java.util.Arrays;

String[] doggoless = 
    Arrays.stream(dog)
        .filter(word -> !"doggo".equals(word))
        .toArray(String[]::new);
gabeg
  • 149
  • 2
0

Here's my own attempt. It may be faster than some other code because it does not create a new array if it is not needed (streams always do). But it does run in minimum O(n) time.

It is also generic, which makes it more flexible than other code which hard codes the type of the array.

   /**
    * Removes elements from an array.
    * 
    * @param array The array to remove elements from.
    * @param element The element to remove.
    * @return An array with the specified elements removed.
    * @throws NullPointerException if either array or element is null.
    */
   public static <T> T[] remove( T[] array, T element ) {
      int count = 0;
      for( T t : array ) 
         if( element.equals( t ) ) count++;
      if( count == 0 ) return array;
      T[] newArray = (T[])Array.newInstance( array.getClass().getComponentType(), 
              array.length-count );
      for( int i = 0, j = 0; i < array.length; i++ ) {
         if( !element.equals( array[i] ) )
            newArray[j++] = array[i];
      }
      return newArray;
   }

Testing:

  String[] test1 = { "foo", "bar", "foo", "bar" };
  String[] result = remove( test1, "bar" );
  System.out.println( Arrays.toString( result ) );
  result = remove( test1, "x" );
  System.out.println( Arrays.toString( result ) );
  result = remove( test1, "foo" );
  System.out.println( Arrays.toString( result ) );
  result = remove( result, "bar" );
  System.out.println( Arrays.toString( result ) );
  result = remove( result, "bar" );
  System.out.println( Arrays.toString( result ) );

Output:

run:
[foo, foo]
[foo, bar, foo, bar]
[bar, bar]
[]
[]
BUILD SUCCESSFUL (total time: 2 seconds)
markspace
  • 10,621
  • 3
  • 25
  • 39