[java] How to remove all elements in String array in java?

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

This question is related to java arrays

The answer is


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


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

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


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`` }**


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.


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.