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

Java对比两个WordCount对象数组添加缺失元素结果异常排查

问题根因

代码的核心错误是tracker计数器的重置位置不对:
目前仅在匹配到缺失元素、往列表新增对象时才会重置tracker为0,前面两次匹配到存在的元素("I"、"love")时,tracker会持续累加为1、2,到遍历第二个数组第三个元素"me"时,tracker初始值已经是2,就算没有匹配到任何元素也不会满足tracker == 0的条件,自然不会把"me"添加到列表中。

另外WordCount类的构造方法还存在一个隐性bug:if (count < 0) count = 0;赋值的是局部参数count,不是类的成员变量this.count,计数小于0的兜底逻辑不会生效。

修复方案

1. 调整tracker重置位置

每次遍历第二个数组的新元素时,先把tracker重置为0即可,还可以新增匹配到就跳出内层循环的逻辑优化性能。

2. 修复WordCount构造方法的隐性bug

修复后完整代码如下:

WordCount类

public class WordCount {
    private String word;
    private int count;

    public WordCount(String word, int count) {
        this.word = word;
        // 修复赋值对象错误
        this.count = Math.max(count, 0);
    }
    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }
    
    // 重写toString方便输出验证
    @Override
    public String toString() {
        return "(\"" + word + "\", " + count + ")";
    }
}

Main方法

public static void main(String arg[]) {
    WordCount[] first;
    first = new WordCount[3];
    first[0] = new WordCount("I", 1);
    first[1] = new WordCount("love", 1);
    first[2] = new WordCount("you", 1);
    ArrayList<WordCount> list = new ArrayList<>(Arrays.asList(first));
    WordCount[] second;
    second = new WordCount[3];
    second[0] = new WordCount("I", 1);
    second[1] = new WordCount("love", 1);
    second[2] = new WordCount("me", 1);
    for (int i = 0; i < second.length; i++) {
        // 每次遍历第二个数组的新元素前,重置计数器
        int tracker = 0;
        for (int j = 0; j < first.length; j++) {
            if (second[i].getWord().equals(first[j].getWord())) {
                tracker++;
                // 匹配到就可以跳出内层循环,优化性能
                break;
            }
        }
        if (tracker == 0) {
            WordCount a = new WordCount(second[i].getWord(), 0);
            list.add(a);
        }
    }
    WordCount[] lastList = list.toArray(new WordCount[0]);
    // 输出验证,结果符合预期:[("I", 1), ("love", 1), ("you", 1), ("me", 0)]
    System.out.println(Arrays.asList(lastList));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:06:06