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

braX
  • 11,506
  • 5
  • 20
  • 33
Karthik
  • 4,943
  • 19
  • 53
  • 86
  • 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? – CoolBeans Dec 21 '11 at 06:31
  • remove all the elements ..... – Karthik Dec 21 '11 at 06:32
  • So you want your `String[5]` to be `String[0]`? – Paul Dec 21 '11 at 06:34
  • 1
    Does this answer your question? [Empty an array in Java / processing](https://stackoverflow.com/questions/4208655/empty-an-array-in-java-processing) – Mr. Jain Jun 17 '20 at 00:43

6 Answers6

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 );
Nate W.
  • 9,141
  • 6
  • 43
  • 65
  • 2
    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. – milanchandna Jan 23 '17 at 08:45
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.

Artem
  • 4,347
  • 2
  • 22
  • 22
4

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

Vaandu
  • 4,857
  • 12
  • 49
  • 75
4

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

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

Carol
  • 407
  • 6
  • 14
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.

fyr
  • 20,227
  • 7
  • 37
  • 53
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`` }**