问题
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
回答1:
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
回答2:
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.
回答3:
Reassign again. Like example = new String[(size)]
回答4:
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
回答5:
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.
回答6:
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``
}**
来源:https://stackoverflow.com/questions/8585879/how-to-remove-all-elements-in-string-array-in-java