Merge pull request #9427 from alimate/BAEL-4153

BAEL-4153: Polluting the Heap
This commit is contained in:
Eric Martin 2020-06-07 11:08:00 -05:00 committed by GitHub
commit d0c9ad62ea
1 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,40 @@
package com.baeldung.varargs;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class HeapPollutionUnitTest {
@Test(expected = ClassCastException.class)
public void givenGenericVararg_whenUsedUnsafe_shouldThrowClassCastException() {
String one = firstOfFirst(Arrays.asList("one", "two"), Collections.emptyList());
assertEquals("one", one);
}
@Test(expected = ClassCastException.class)
public void givenGenericVararg_whenRefEscapes_mayCauseSubtleBugs() {
String[] args = returnAsIs("One", "Two");
}
private static String firstOfFirst(List<String>... strings) {
List<Integer> ints = Collections.singletonList(42);
Object[] objects = strings;
objects[0] = ints;
return strings[0].get(0);
}
private static <T> T[] toArray(T... arguments) {
return arguments;
}
private static <T> T[] returnAsIs(T a, T b) {
return toArray(a, b);
}
}