|
| 1 | +package pl.mperor.lab.java.quirk; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Assertions; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +public class IntegerCacheTest { |
| 7 | + |
| 8 | + @Test |
| 9 | + public void testAutoboxingWithinCacheRangeSharesInstance() { |
| 10 | + Integer a = 127, b = 127; |
| 11 | + Assertions.assertTrue(a == b, "autoboxing delegates to Integer.valueOf, which caches -128..127"); |
| 12 | + } |
| 13 | + |
| 14 | + @Test |
| 15 | + public void testAutoboxingOutsideCacheRangeCreatesNewInstance() { |
| 16 | + Integer a = 128, b = 128; |
| 17 | + Assertions.assertFalse(a == b, "128 is outside the cached range, so valueOf allocates a new Integer each time"); |
| 18 | + } |
| 19 | + |
| 20 | + @SuppressWarnings("removal") |
| 21 | + @Test |
| 22 | + public void testExplicitConstructorNeverUsesTheCache() { |
| 23 | + Integer a = new Integer(127), b = new Integer(127); |
| 24 | + Assertions.assertFalse(a == b, "new Integer(int) always allocates, unlike the deprecated-for-removal valueOf cache"); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + public void testOtherIntegralWrappersCacheMinus128To127() { |
| 29 | + Long l1 = 127L, l2 = 127L; |
| 30 | + Short s1 = 127, s2 = 127; |
| 31 | + Byte b1 = (byte) 127, b2 = (byte) 127; |
| 32 | + Assertions.assertTrue(l1 == l2); |
| 33 | + Assertions.assertTrue(s1 == s2); |
| 34 | + Assertions.assertTrue(b1 == b2, "byte's full range fits in the cache, so every boxed byte is shared"); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void testCharacterCaches0To127() { |
| 39 | + Character c1 = 'A', c2 = 'A'; |
| 40 | + Assertions.assertTrue(c1 == c2, "'A' is 65, inside Character's 0..127 cache"); |
| 41 | + |
| 42 | + char outsideCache = 200; |
| 43 | + Character c3 = outsideCache, c4 = outsideCache; |
| 44 | + Assertions.assertFalse(c3 == c4, "200 is outside Character's cache"); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + public void testFloatingPointWrappersAreNeverCached() { |
| 49 | + Double d1 = 1.0, d2 = 1.0; |
| 50 | + Float f1 = 1.0f, f2 = 1.0f; |
| 51 | + Assertions.assertFalse(d1 == d2, "Double.valueOf never caches, even for small values"); |
| 52 | + Assertions.assertFalse(f1 == f2, "Float.valueOf never caches either"); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + public void testEqualsIsTheCorrectComparisonRegardlessOfCaching() { |
| 57 | + Integer a = 128, b = 128; |
| 58 | + Assertions.assertFalse(a == b); |
| 59 | + Assertions.assertTrue(a.equals(b), "equals compares values, so it is unaffected by whether the cache kicked in"); |
| 60 | + } |
| 61 | + |
| 62 | + @Test |
| 63 | + public void testUnboxingNullThrowsNullPointerException() { |
| 64 | + Integer boxed = null; |
| 65 | + Assertions.assertThrows(NullPointerException.class, () -> { |
| 66 | + int unboxed = boxed; |
| 67 | + }, "unboxing null calls Integer.intValue() on a null reference"); |
| 68 | + } |
| 69 | +} |
0 commit comments