如何不用 List.clear() 方法 就清空 list 中的 所有元素(中兴面试)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

// 涛哥 1609251501
// 如何不用 List.clear() 方法 就清空 list 中的 所有元素.
public class MyList {
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<>(Arrays.asList("1","2","3","4"));
		Iterator<String> it = list.iterator();
		
		while(it.hasNext()) {
			it.next(); // return ; cursor++;
			it.remove(); // cursor
		}
		System.out.println(list);
	}
}


代码分析:

it.next() 源码中:  先返回 当前 cursor 所指向的 value, 之后 cursor 在 自加;

 public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

it.remove() 源码中: AraryList.remove() 方法 删除元素的方法是 将 后面的元素 全部向前挪动一个位置;且 cursor 等于上一次 更改位置的index;

public void remove() { // ArrayList$Itr.remove()
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet); // 调用 ArrayList.remove() 方法
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
 public E remove(int index) { // ArrayList.remove()方法
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved); // 这里是 深度拷贝。
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值