BAEL-3131 Guide to Java HashMap (#8229)

http://jira.baeldung.com/browse/BAEL-3130
This commit is contained in:
Maiklins 2019-11-24 12:59:09 +01:00 committed by Grzegorz Piwowarek
parent b9e46ff27a
commit de82f1c805
2 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,70 @@
package com.baeldung.overflow;
import java.math.BigInteger;
public class Overflow {
public static void showIntegerOverflow() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++, value++) {
System.out.println(value);
}
}
public static void noOverflowWithBigInteger() {
BigInteger largeValue = new BigInteger(Integer.MAX_VALUE + "");
for(int i = 0; i < 4; i++) {
System.out.println(largeValue);
largeValue = largeValue.add(BigInteger.ONE);
}
}
public static void exceptionWithAddExact() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++) {
System.out.println(value);
value = Math.addExact(value, 1);
}
}
public static int addExact(int x, int y) {
int r = x + y;
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("int overflow");
}
return r;
}
public static void demonstrateUnderflow() {
for(int i = 1073; i <= 1076; i++) {
System.out.println("2^" + i + " = " + Math.pow(2, -i));
}
}
public static double powExact(double base, double exponent)
{
if(base == 0.0) {
return 0.0;
}
double result = Math.pow(base, exponent);
if(result == Double.POSITIVE_INFINITY ) {
throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY");
} else if(result == Double.NEGATIVE_INFINITY) {
throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY");
} else if(Double.compare(-0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in negative zero");
} else if(Double.compare(+0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in positive zero");
}
return result;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.math;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class OverflowUnitTest {
@Test
public void positive_and_negative_zero_are_not_always_equal() {
double a = +0f;
double b = -0f;
assertTrue(a == b);
assertTrue(1/a == Double.POSITIVE_INFINITY);
assertTrue(1/b == Double.NEGATIVE_INFINITY);
assertTrue(1/a != 1/b);
}
}