由于函数调用,ArrayList无法添加元素

时间:2017-06-07 14:02:39

标签: java arraylist

在运行下面的代码片段时,循环正常执行,但由于某种原因不会添加元素。

localhost

2 个答案:

答案 0 :(得分:1)

您要从列表中删除int i而不是计算值。你执行contains方法,你应该删除该部分。每次运行它将删除你在参数中插入的任何内容。所以每次你添加一些东西,然后只是方法并删除你刚添加的东西。

答案 1 :(得分:0)

作业相当有趣,但你试图做的方式实在太贵了(而且非常错误,因为你在迭代过程中修改了列表)

所以这里有一些改进:

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    IntStream.range(5, 500)  
        .filter(i -> !check(list,i))    // check first
        .forEach( i -> list.add(i));    // add after
    System.out.println(list);
}
// we assume (rightly so) that list is ordered
private static boolean check(List<Integer> list, int value) {
    boolean found = false;
    for(int j=0; j < list.size(); j++){
        Integer leftSide = list.get(j);
        if(leftSide > value/2){   
            break;                  // as the check is symmetrical, stop after value/2 has been overtaken
        }
        Integer complementaryValue = value - leftSide;
        for(int k=j+1; k < list.size(); k++){  // iterate over the rest of the list (because right is necessarily > left)
            Integer rightSide = list.get(k);
            if(rightSide > complementaryValue){  
                break;              // no need to continue further
            }
            if(complementaryValue.equals(rightSide)){
                found = true;
                System.out.println(value+" = "+leftSide+" + "+rightSide);
                break;
            }
        }
        if(found){
            break;  // or return true
        }
    }
    return found;
}

你可以尝试一下。

这仍然不是最优的,仍然可以在内循环上完成工作。对补充值的二分法搜索会更好。

最终名单是

  

[5,6,7,8,9,10,20,21,22,23,24,35,36,37,38,39,50,51,52,53,54,65,66, 67,68,69,80,81,82,83,84,95,96,97,98,99,110,111,112,113,114,125,126,127,128,129,140,​​141, 142,143,144,155,156,157,158,159,170,171,172,173,174,185,186,187,188,189,200,201,202,203,204,215,216, 217,218,219,230,231,232,233,234,245,246,247,248,249,260,261,262,263,264,275,276,277,278,279,290,291, 292,293,283,305,306,307,308,309,320,321,322,323,324,335,336,337,338,339,350,351,352,353,354,365,366, 367,368,369,380,381,382,383,384,395,396,397,398,399,410,411,412,413,414,425,426,427,428,429,440,441, 442,443,444,455,456,457,458,459,470,471,472,473,474,485,486,487,488,489]