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); }
I can't understand the code for mincapacity - elementdata.length > 0
. Why not use mincapacity > elementdata.length.
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"); } }
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!