简体   繁体   English

Java循环奇怪的行为

[英]Java loop strange behaviour

I have this split method inside which I have a loop. 我有一个拆分方法,里面有一个循环。 This loop is running 4 times but it should run 5 times. 此循环运行4次,但应运行5次。 Any idea why is it behaving like this? 知道为什么会这样吗?

public static <T> List<List<T>> split(List<T> bigCollection, int maxBatchSize) {
        List<List<T>> result = new ArrayList<List<T>>();

        if (CollectionUtils.isEmpty(bigCollection)) {
            // return empty list
        } else if (bigCollection.size() < maxBatchSize) {
            result.add(bigCollection);
        } else {
            for (int i = 0; (i + maxBatchSize) <= bigCollection.size(); i = i + maxBatchSize) {
                result.add(bigCollection.subList(i, i + maxBatchSize));
            }

            if (bigCollection.size() % maxBatchSize > 0) {
                result.add(bigCollection.subList((int) (bigCollection.size() / maxBatchSize) * maxBatchSize,
                    bigCollection.size()));
            }
        }

        return result;
    }

    public static void main(String[] args) {
        List<String> coll = new ArrayList<String>();
        coll.add("1");
        coll.add("2");
        coll.add("3");
        coll.add("4");
        coll.add("5");
        coll.add("6");
        coll.add("7");
        coll.add("8");

        System.out.println(split(coll, 2));
    }

Output - [[1, 2], [3, 4], [5, 6], [7, 8]] 输出-[[1、2],[3、4],[5、6],[7、8]

According to me this code should break when loop runs the fifth time and it tries to perform sublist function. 据我说,这段代码应该在循环第五次运行时中断,并尝试执行子列表功能。

When you're at iteration 4, your loop condititoin is like this : 在迭代4时,您的循环条件是这样的:

(i + maxBatchSize) <= bigCollection.size()
 6 + 2             <= 8

So you're going in. But the fifth iteration doesn't respect this condition anymore, because it's like this : 因此,您要进行操作。但是第五次迭代不再遵守此条件,因为它是这样的:

(i + maxBatchSize) <= bigCollection.size()
 8 + 2             <= 8

Don't forget that your condition isn't only on i but on i + maxBatchSize 别忘了,您的情况不仅在i而且在i + maxBatchSize

The following for loop 以下为循环

for (int i = 0; (i + maxBatchSize) <= bigCollection.size(); i = i + maxBatchSize) {
    result.add(bigCollection.subList(i, i + maxBatchSize));
}

goes from 0 to bigCollection.size() - maxBatchSize by steps of maxBatchSize . 从0到bigCollection.size() - maxBatchSize的步长为maxBatchSize In your example, bigCollection has size 8 and maxBatchSize is 2, so the loop goes from 0 to 6 by steps of 2. In total, that makes 4 steps : 0, 2, 4 and 6. 在您的示例中, bigCollection大小为8, maxBatchSize为2,因此循环从0到6的步长为2。总共执行4个步骤: maxBatchSize和6。

The following if 以下如果

if (bigCollection.size() % maxBatchSize > 0)

is not executed because 8 % 2 = 0 (so the subList is not performed). 因为8 % 2 = 0 (所以不执行subList ),所以不执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM