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

Java中如何向ArrayList添加唯一元素?解决重复元素问题

问题分析与解决

你的去重逻辑失效,大概率是泛型类型不匹配导致的,另外代码也有可优化的地方,具体解决如下:

核心问题

如果你的listID声明为ArrayList<String>,但你用Integer.parseInt(line)生成的Integer对象调用contains方法,由于集合里存的是String类型,而判断的是Integer类型,两者类型不匹配,contains永远返回false,所以每一行都会被重复添加。

修复方案

方案1:修正ArrayList泛型并优化代码

确保listID是ArrayList<Integer>类型,同时优化重复解析问题,处理空行和空白字符:

// 正确声明泛型类型的listID
ArrayList<Integer> listID = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
String line;
while ((line = br.readLine()) != null) {
    // 去掉行前后空白字符,避免因空格导致的解析问题
    String trimmedLine = line.trim();
    if (trimmedLine.isEmpty()) {
        continue; // 跳过空行
    }
    Integer id = Integer.parseInt(trimmedLine);
    if (!listID.contains(id)) {
        listID.add(id);
    }
}
// 将遍历操作移到读取循环外,避免重复遍历
for (int i = 0; i < listID.size(); i++) {
    // do stuff
}

方案2:用HashSet高效去重(推荐)

ArrayList的contains方法是O(n)时间复杂度,数据量大时效率低。用HashSet自动去重(add方法会自动忽略重复元素),之后再转成ArrayList,效率更高:

Set<Integer> idSet = new HashSet<>();
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
String line;
while ((line = br.readLine()) != null) {
    String trimmedLine = line.trim();
    if (trimmedLine.isEmpty()) {
        continue;
    }
    idSet.add(Integer.parseInt(trimmedLine));
}
// 将去重后的集合转成ArrayList
ArrayList<Integer> listID = new ArrayList<>(idSet);
// 后续遍历操作
for (int id : listID) {
    // do stuff
}

额外注意点

  • 确保文件中的每行都是有效的整数,否则Integer.parseInt会抛出异常,建议添加try-catch异常处理。
  • 如果需要保留元素的读取顺序,可以用LinkedHashSet代替HashSet,它会维持元素的插入顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:10:16