You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Iterator遍历ArrayList时如何自动跳过null值

实现Iterator跳过null值的修改方案

核心逻辑

我们需要在hasNext()方法中提前完成空值校验和指针位移,保证当hasNext()返回true时,当前指针指向的一定是非null元素,避免在next()中做复杂判断,同时符合Iterator接口的设计规范。

原有代码问题

  1. 原有hasNext()仅判断下标是否越界,未校验当前下标对应元素是否为null
  2. 原有next()没有跳过null元素的逻辑,会直接返回null值
  3. 不符合Iterator规范:无后续元素时next()应抛出NoSuchElementException,而非返回null

修改后的完整代码

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayListIterator implements Iterator<Object> {
    
    int current = 0;

    @Override
    public boolean hasNext() {
        // 循环查找下一个非null元素的位置
        while (current < entryCount()) {
            Object currentElement = get(current);
            if (currentElement != null) {
                // 找到非null元素,返回true
                return true;
            }
            // 是null,指针后移继续找
            current++;
        }
        // 遍历完所有元素都没找到非null值,返回false
        return false;
    }

    @Override
    public Object next() {
        // 先调用hasNext()确保指针已经指向非null元素,同时处理无元素的场景
        if (!hasNext()) {
            throw new NoSuchElementException("没有更多非null元素");
        }
        Object result = null;
        try {
            result = get(current);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            throw new NoSuchElementException("下标越界");
        } catch (IOException e) {
            e.printStackTrace();
            // 若自定义get方法不会抛出IO异常,可直接删除该catch分支
            throw new RuntimeException("读取元素失败", e);
        }
        // 指针后移,等待下一次查找
        current++;
        return result;
    }
}

效果验证

针对测试用例["123", null, "433"],遍历逻辑如下:

  1. 第一次调用hasNext(),current=0,元素为"123"非null,返回true
  2. 调用next(),返回"123",current变为1
  3. 第二次调用hasNext(),current=1对应元素为null,current自增到2,对应元素为"433"非null,返回true
  4. 调用next(),返回"433",current变为3
  5. 第三次调用hasNext(),current=3等于总长度3,返回false,遍历结束
    最终返回的元素就是["123", "433"],符合预期。

内容的提问来源于stack exchange,提问作者Frank Fiumara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:48:03