16

I would like to remove all the elements in the String array for instance:

String example[]={"Apple","Orange","Mango","Grape","Cherry"}; 

Is there any simple to do it,any snippet on it will be helpful.Thanks

4
  • Remove from what? Do you just want to remove from the example[] array? Or do you have another array where you want to remove the elements present in example array? Commented Dec 21, 2011 at 6:31
  • remove all the elements ..... Commented Dec 21, 2011 at 6:32
  • So you want your String[5] to be String[0]? Commented Dec 21, 2011 at 6:34
  • 1
    Does this answer your question? Empty an array in Java / processing Commented Jun 17, 2020 at 0:43

6 Answers 6

55

If example is not final then a simple reassignment would work:

example = new String[example.length];

This assumes you need the array to remain the same size. If that's not necessary then create an empty array:

example = new String[0];

If it is final then you could null out all the elements:

Arrays.fill( example, null );
Sign up to request clarification or add additional context in comments.

1 Comment

First approach(reassignment) should only be preferred if it has to be done once or twice or few times. Otherwise every time you will end up allocating memory for new arrays. Also Second approach can not be used for primitive arrays.
9
example = new String[example.length];

If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

Comments

4

Reassign again. Like example = new String[(size)]

Comments

4

list.clear() is documented for clearing the ArrayList.

list.removeAll() has no documentation at all in Eclipse.

Comments

2

Usually someone uses collections if something frequently changes.

E.g.

    List<String> someList = new ArrayList<String>();
    // initialize list
    someList.add("Mango");
    someList.add("....");
    // remove all elements
    someList.clear();
    // empty list

An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.

Comments

0

Just Re-Initialize the array

example = new String[size]

or If it is inside a running loop,Just Re-declare it again,

**for(int i=1;i<=100;i++) { String example = new String[size] //Your code goes here`` }**

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.