另加20分java 中ArrayList 中去除空的值怎么去!!

来源:百度知道 编辑:UC知道 时间:2024/06/03 08:53:42
我通过remove(int) 将ArrayList中有的去掉了 可他那个位置只是空出来了 比如 list 的长度为10 我能过 list.remove(5) 后它的长度还是10 只是第6个变为了null了 怎么把这null去掉呀?

List list = new ArrayList();
for(int i=0;i<10;i++){
list.add(i);
}
System.out.println("删除前:"+Arrays.toString(list.toArray()) + "\t list大小"+list.size());
list.remove(5);
System.out.println("删除后:"+ Arrays.toString(list.toArray())+ "\t list大小"+list.size());

结果:
删除前:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list大小10
删除后:[0, 1, 2, 3, 4, 6, 7, 8, 9] list大小9

首先 你将一个ArrayList的容器初始化长度为10 然后你查看下这个容器的长度是多少

对 无论有没有参数他的长度都为十 因为你初始化他的长度为十 明白米?

我刚查了API,估计你是想用TrimToSize方法吧!

remove
public E remove(int index)移除此列表中指定位置上的元素。向左移动所有后续元素(将其索引减 1)。

指定者:
接口 List<E> 中的 remove
覆盖:
类 AbstractList<E> 中的 remove
参数:
index - 要移除的元素的索引
返回:
从列表中移除的元素
抛出:
IndexOutOfBoundsException - 如果索引超出范围 (index < 0 || index >= size())

-----------------------------------------------------------------