Difference between if (a - b < 0) and if (a < b)

后端 未结 4 1642
北荒
北荒 2020-12-22 15:47

I was reading Java\'s ArrayList source code and noticed some comparisons in if-statements.

In Java 7, the method grow(int) uses

if (newC         


        
4条回答
  •  误落风尘
    2020-12-22 16:09

    Looking at the code:

    int newCapacity = oldCapacity + (oldCapacity >> 1);
    

    If oldCapacity is quite large, this will overflow, and newCapacity will be a negative number. A comparison like newCapacity < oldCapacity will incorrectly evaluate true and the ArrayList will fail to grow.

    Instead, the code as written (newCapacity - minCapacity < 0 returns false) will allow the negative value of newCapacity to be further evaluated in the next line, resulting in recalculating newCapacity by invoking hugeCapacity (newCapacity = hugeCapacity(minCapacity);) to allow for the ArrayList to grow up to MAX_ARRAY_SIZE.

    This is what the // overflow-conscious code comment is trying to communicate, though rather obliquely.

    So, bottom line, the new comparison protects against allocating an ArrayList larger than the predefined MAX_ARRAY_SIZE while allowing it to grow right up to that limit if needed.

提交回复
热议问题