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.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With