Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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

like image 337
Karthik Avatar asked Dec 21 '11 06:12

Karthik


People also ask

How do you remove duplicate values from a String array in Java?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do I remove all elements from a String array?

Using List.First Create an empty List of Array. Insert all elements of the array into the list. Remove all elements which is you want to remove. Convert the list back to an array and return it.

How do you remove all elements from a String array in Java?

The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);


1 Answers

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 );
  • See: void Arrays#fill(Object[], Object)
  • Consider using an ArrayList or similar collection
like image 194
Nate W. Avatar answered Nov 09 '22 01:11

Nate W.