编辑:
数组中带有空值的点已被清除。对不起我的cmets。
原文:
嗯……线
array = list.toArray(array);
用 null 替换数组中已删除元素所在的所有间隙。这可能是危险的,因为元素被移除了,但数组的长度保持不变!
如果您想避免这种情况,请使用新的数组作为 toArray() 的参数。如果您不想使用 removeAll,则可以使用 Set:
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
Set<String> asSet = new HashSet<String>(Arrays.asList(array));
asSet.remove("a");
array = asSet.toArray(new String[] {});
System.out.println(Arrays.toString(array));
给予:
[a, bc, dc, a, ef]
[dc, ef, bc]
Chris Yester Young 输出当前接受的答案:
[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]
用代码
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
System.out.println(Arrays.toString(array));
没有留下任何空值。