Java基础-易错点

List.remove

注意有两个重载方法remove(int)和remove(Object), 很容易混淆

案例:

Map<String, Integer> unionMap = new HashMap<>();
for (int i = 0; i < insertList.size(); i++) {
    CstGoods cstGoods = insertList.get(i);
    String unionKey = String.join("_", cstGoods.getSpCode(), cstGoods.getCostType(), String.valueOf(cstGoods.getCostScene()), cstGoods.getBgDate().toString(), cstGoods.getEdDate().toString());
    if (unionMap.containsKey(unionKey)) {
        unionMap.put(unionKey, i);
        //特别注意这一行
        Integer index = unionMap.get(unionKey);
        insertList.remove(index);
        i--;
    } else {
        unionMap.put(unionKey, i);
    }
}

本意是移除已经存在的列. 但是问题就出在list.remove. 如果remove方法的入参传入的是包装类型,自然就会执行remove(Object), 那么结果肯定是移除不了这个重复对象. 所以需要将Integer index = unionMap.get(unionKey); 改为 int index = unionMap.get(unionKey);.要不然会导致死循环

修正后的代码

Map<String, Integer> unionMap = new HashMap<>();
for (int i = 0; i < insertList.size(); i++) {
    CstGoods cstGoods = insertList.get(i);
    String unionKey = String.join("_", cstGoods.getSpCode(), cstGoods.getCostType(), String.valueOf(cstGoods.getCostScene()), cstGoods.getBgDate().toString(), cstGoods.getEdDate().toString());
    if (unionMap.containsKey(unionKey)) {
        unionMap.put(unionKey, i);
        //特别注意这一行
        int index = unionMap.get(unionKey);
        insertList.remove(index);
        i--;
    } else {
        unionMap.put(unionKey, i);
    }
}