Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the JDK 1.8 source code, why use A-B> 0 to determine which one is larger, not A> B?

Tags:

java

java-8

As a beginner, I read the source code of JDK1.8 recently. I faced the question that why use A-B> 0 to determine which one is larger, not A> B?

The code of below is in java/util/ArrayList.java:236

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

I can't understand the code of minCapacity - elementData.length > 0. Why not use minCapacity > elementData.length.

like image 323
shy Ren Avatar asked Nov 02 '25 19:11

shy Ren


1 Answers

Probably to prevent overflow of minCapacity, check this example:

 public static void main(String[] args) {
    int elementDataLength = 10;
    int minCapacity = Integer.MAX_VALUE; // very big

    minCapacity += 1; // accidentally overflow it

    if (minCapacity > elementDataLength) {
        System.out.println("Will not work: minCapacity=-2147483647 elementDataLength=10");
    }
    if (minCapacity - elementDataLength > 0) {
        System.out.println("Will work: minCapacity - elementDataLength = 2147483638");
    }
}
like image 154
Python Dev Avatar answered Nov 04 '25 10:11

Python Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!