Home > Java > body text

In the JDK 1.8 source code, why is A-B>0 used to determine which one is bigger instead of A>B?

WBOY
Release: 2024-02-06 11:36:03
forward
1127 people have browsed it
Question content

As a beginner, I recently read the source code of jdk1.8. The question I'm having is why is a-b> 0 used to determine which is larger, rather than a> b?

The following code is in java/util/arraylist.java:236

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

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

I can't understand the code for mincapacity - elementdata.length > 0. Why not use mincapacity > elementdata.length.


Correct answer


Probably to prevent mincapacity overflow, please check the following 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");
    }
}
Copy after login

The above is the detailed content of In the JDK 1.8 source code, why is A-B>0 used to determine which one is bigger instead of A>B?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template