14

Possible Duplicate:
Removing an element from an Array (Java)

How to remove specific String array value for example

String[] str_array = {"item1","item2","item3"};

i want to remove "item2" from str_array pls help me i want output like

String[] str_array = {"item1","item3"};

5
  • You needed to copy to a new array if you want the length to reduce also. Use ArrayList if you want dynamic size array Commented Oct 10, 2012 at 5:10
  • You have to iterate the Array and compare your value Commented Oct 10, 2012 at 5:11
  • i know remove value from arraylist we use "list.remove()" but i need is there any property to remove string in string array Commented Oct 10, 2012 at 5:14
  • @Vicky: No. There is no such property. Commented Oct 10, 2012 at 5:16
  • The arrays by themselves don't have these methods. If you want to do it in a single and effective line, you should follow PeterLawrey's advice: stackoverflow.com/a/644719/1065197 Commented Oct 10, 2012 at 5:16

3 Answers 3

49

I would do it as follows:

String[] str_array = {"item1","item2","item3"};
List<String> list = new ArrayList<String>(Arrays.asList(str_array));
list.remove("item2");
str_array = list.toArray(new String[0]);
Sign up to request clarification or add additional context in comments.

5 Comments

Inefficient compared to use of System.arraycopy, especially when used multiple times.
@Vulcan, thanks for your comment, would you mind updating my answer to show how to use System.arraycopy here? Thanks.
@Vikdor I'll post an answer that uses it, one moment.
@Vikdor Sorry for the delay, got distracted with something. I've posted the answer though.
this really useful... This answer helped me loads
7

If you must use arrays, System.arraycopy is the most efficient, scalable solution. However, if you must remove one element from an array several times, you should use an implementation of List rather than an array.

The following utilizes System.arraycopy in order to achieve the desired effect.

public static Object[] remove(Object[] array, Object element) {
    if (array.length > 0) {
        int index = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(element)) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            Object[] copy = (Object[]) Array.newInstance(array.getClass()
                    .getComponentType(), array.length - 1);
            if (copy.length > 0) {
                System.arraycopy(array, 0, copy, 0, index);
                System.arraycopy(array, index + 1, copy, index, copy.length - index);
            }
            return copy;
        }
    }
    return array;
}

Also, you can increase the method's efficiency if you know that your array consists of only Comparable objects. You can use Arrays.sort to sort them before passing them through the remove method, modified to use Arrays.binarySearch to find index rather than a for loop, raising that portion of the method's efficiency from O(n) to O(nlogn).

6 Comments

It's not very nice to get an Object[] back when you want a String[]. Array.newInstance lets you construct an array of arbitrary type.
@gustafc Good point. The downside to that is slightly slower execution time though.
It's also worth noting that O(n log n) isn't necessarily faster than O(n) as Big O only tells you how the cost of handling n+1 elements is compared to handling n elements with the same algorithm. The constant cost associated with sorting may well outweigh the benefits of binary search (especially for small arrays).
Array.newInstance might be slower, but it is not necessarily so. HotSpot can optimize it to be just as fast as a regular array instantiation in most cases. Either way, you end up with a more robust and correct program.
Indeed. Also, if that part of the code becomes a bottleneck, arrays probably aren't the most appropriate data structure for your program.
|
4

Other Option is to copy array to other array accept than remove item.

 public static String[] removeItemFromArray(String[] input, String item) {
    if (input == null) {
        return null;
    } else if (input.length <= 0) {
        return input;
    } else {
        String[] output = new String[input.length - 1];
        int count = 0;
        for (String i : input) {
            if (!i.equals(item)) {
                output[count++] = i;
            }
        }
        return output;
    }
}

1 Comment

Note, this will remove all instances of item from the input array rather than just one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.