How to remove all elements in String array in java?

穿精又带淫゛_ 提交于 2019-12-18 13:19:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!