如何从ArrayList中删除空白项目。不要删除索引

public class ArrayListTest { public static void main(String[] args) { ArrayList al=new ArrayList(); al.add(""); al.add("name"); al.add(""); al.add(""); al.add(4, "asd"); System.out.println(al); } } 

o / p [,name ,,, asd]欲望O / p [name,asd]

您可以使用removeAll(Collection c)

删除同样包含在指定集合中的所有此集合的元素

 al.removeAll(Arrays.asList(null,"")); 

这将删除列表中所有null或等于""元素。

输出:

 [name, asd] 

您可以按值删除对象。

 while(al.remove("")); 

迭代列表,读取每个值,将其与空字符串""进行比较,如果是,则将其删除:

 Iterator it = al.iterator(); while(it.hasNext()) { //pick up the value String value= (String)it.next(); //if it's empty string if ("".equals(value)) { //call remove on the iterator, it will indeed remove it it.remove(); } } 

另一种选择是在列表中有空字符串时调用List的remove()方法:

 while(list.contains("")) { list.remove(""); } 
 List al=new ArrayList(); ................... for(Iterator it = al.iterator(); it.hasNext();) { String elem = it.next(); if ("".equals(elem)) { it.remove(); } } 

我不评论这段代码。 你应该自己学习。 请注意所有细节。