Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/util/List/ListDefaults.java
38812 views
/*1* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.util.ArrayList;24import java.util.Arrays;25import java.util.Collection;26import java.util.Collections;27import java.util.Comparator;28import java.util.List;29import java.util.LinkedList;30import java.util.Stack;31import java.util.Vector;32import java.util.concurrent.CopyOnWriteArrayList;33import java.util.concurrent.atomic.AtomicBoolean;34import java.util.concurrent.atomic.AtomicInteger;3536import org.testng.annotations.DataProvider;37import org.testng.annotations.Test;3839import static org.testng.Assert.assertEquals;40import static org.testng.Assert.assertFalse;41import static org.testng.Assert.assertTrue;42import static org.testng.Assert.fail;4344import java.lang.reflect.Constructor;45import java.util.ConcurrentModificationException;46import java.util.function.Consumer;47import java.util.function.Function;48import java.util.function.Predicate;49import java.util.function.Supplier;5051/**52* @test53* @summary Unit tests for extension methods on List54* @bug 8023367 803710655* @library ../Collection/testlibrary56* @build CollectionAsserts CollectionSupplier ExtendsAbstractList57* @run testng ListDefaults58*/59public class ListDefaults {6061// Suppliers of lists that can support structural modifications62private static final List<Function<Collection, List>> LIST_STRUCT_MOD_SUPPLIERS = Arrays.asList(63java.util.ArrayList::new,64java.util.LinkedList::new,65java.util.Vector::new,66java.util.concurrent.CopyOnWriteArrayList::new,67ExtendsAbstractList::new68);6970// Suppliers of lists that can support in place modifications71private static final List<Function<Collection, List>> LIST_SUPPLIERS = Arrays.asList(72java.util.ArrayList::new,73java.util.LinkedList::new,74java.util.Vector::new,75java.util.concurrent.CopyOnWriteArrayList::new,76ExtendsAbstractList::new,77c -> Arrays.asList(c.toArray())78);7980// Suppliers of lists supporting CMEs81private static final List<Function<Collection, List>> LIST_CME_SUPPLIERS = Arrays.asList(82java.util.ArrayList::new,83java.util.Vector::new84);8586private static final Predicate<Integer> pEven = x -> 0 == x % 2;87private static final Predicate<Integer> pOdd = x -> 1 == x % 2;8889private static final Comparator<Integer> BIT_COUNT_COMPARATOR =90(x, y) -> Integer.bitCount(x) - Integer.bitCount(y);9192private static final Comparator<AtomicInteger> ATOMIC_INTEGER_COMPARATOR =93(x, y) -> x.intValue() - y.intValue();9495private static final int SIZE = 100;96private static final int SUBLIST_FROM = 20;97private static final int SUBLIST_TO = SIZE - 5;98private static final int SUBLIST_SIZE = SUBLIST_TO - SUBLIST_FROM;99100// call the callback for each recursive subList101private void trimmedSubList(final List<Integer> list, final Consumer<List<Integer>> callback) {102int size = list.size();103if (size > 1) {104// trim 1 element from both ends105final List<Integer> subList = list.subList(1, size - 1);106callback.accept(subList);107trimmedSubList(subList, callback);108}109}110111@DataProvider(name="listProvider", parallel=true)112public static Object[][] listCases() {113final List<Object[]> cases = new LinkedList<>();114cases.add(new Object[] { Collections.emptyList() });115cases.add(new Object[] { new ArrayList<>() });116cases.add(new Object[] { new LinkedList<>() });117cases.add(new Object[] { new Vector<>() });118cases.add(new Object[] { new Stack<>() });119cases.add(new Object[] { new CopyOnWriteArrayList<>() });120cases.add(new Object[] { Arrays.asList() });121122List<Integer> l = Arrays.asList(42);123cases.add(new Object[] { new ArrayList<>(l) });124cases.add(new Object[] { new LinkedList<>(l) });125cases.add(new Object[] { new Vector<>(l) });126Stack<Integer> s = new Stack<>(); s.addAll(l);127cases.add(new Object[]{s});128cases.add(new Object[] { new CopyOnWriteArrayList<>(l) });129cases.add(new Object[] { l });130return cases.toArray(new Object[0][cases.size()]);131}132133@Test(dataProvider = "listProvider")134public void testProvidedWithNull(final List<Integer> list) {135try {136list.forEach(null);137fail("expected NPE not thrown");138} catch (NullPointerException npe) {}139try {140list.replaceAll(null);141fail("expected NPE not thrown");142} catch (NullPointerException npe) {}143try {144list.removeIf(null);145fail("expected NPE not thrown");146} catch (NullPointerException npe) {}147try {148list.sort(null);149} catch (Throwable t) {150fail("Exception not expected: " + t);151}152}153154@Test155public void testForEach() {156@SuppressWarnings("unchecked")157final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);158for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {159final List<Integer> original = test.expected;160final List<Integer> list = test.collection;161162try {163list.forEach(null);164fail("expected NPE not thrown");165} catch (NullPointerException npe) {}166CollectionAsserts.assertContents(list, original);167168final List<Integer> actual = new LinkedList<>();169list.forEach(actual::add);170CollectionAsserts.assertContents(actual, list);171CollectionAsserts.assertContents(actual, original);172173if (original.size() > SUBLIST_SIZE) {174final List<Integer> subList = original.subList(SUBLIST_FROM, SUBLIST_TO);175final List<Integer> actualSubList = new LinkedList<>();176subList.forEach(actualSubList::add);177assertEquals(actualSubList.size(), SUBLIST_SIZE);178for (int i = 0; i < SUBLIST_SIZE; i++) {179assertEquals(actualSubList.get(i), original.get(i + SUBLIST_FROM));180}181}182183trimmedSubList(list, l -> {184final List<Integer> a = new LinkedList<>();185l.forEach(a::add);186CollectionAsserts.assertContents(a, l);187});188}189}190191@Test192public void testRemoveIf() {193@SuppressWarnings("unchecked")194final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_STRUCT_MOD_SUPPLIERS, SIZE);195for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {196final List<Integer> original = test.expected;197final List<Integer> list = test.collection;198199try {200list.removeIf(null);201fail("expected NPE not thrown");202} catch (NullPointerException npe) {}203CollectionAsserts.assertContents(list, original);204205final AtomicInteger offset = new AtomicInteger(1);206while (list.size() > 0) {207removeFirst(original, list, offset);208}209}210211for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {212final List<Integer> original = test.expected;213final List<Integer> list = test.collection;214list.removeIf(pOdd);215for (int i : list) {216assertTrue((i % 2) == 0);217}218for (int i : original) {219if (i % 2 == 0) {220assertTrue(list.contains(i));221}222}223list.removeIf(pEven);224assertTrue(list.isEmpty());225}226227for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {228final List<Integer> original = test.expected;229final List<Integer> list = test.collection;230final List<Integer> listCopy = new ArrayList<>(list);231if (original.size() > SUBLIST_SIZE) {232final List<Integer> subList = list.subList(SUBLIST_FROM, SUBLIST_TO);233final List<Integer> subListCopy = new ArrayList<>(subList);234listCopy.removeAll(subList);235subList.removeIf(pOdd);236for (int i : subList) {237assertTrue((i % 2) == 0);238}239for (int i : subListCopy) {240if (i % 2 == 0) {241assertTrue(subList.contains(i));242} else {243assertFalse(subList.contains(i));244}245}246subList.removeIf(pEven);247assertTrue(subList.isEmpty());248// elements outside the view should remain249CollectionAsserts.assertContents(list, listCopy);250}251}252253for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {254final List<Integer> list = test.collection;255trimmedSubList(list, l -> {256final List<Integer> copy = new ArrayList<>(l);257l.removeIf(pOdd);258for (int i : l) {259assertTrue((i % 2) == 0);260}261for (int i : copy) {262if (i % 2 == 0) {263assertTrue(l.contains(i));264} else {265assertFalse(l.contains(i));266}267}268});269}270}271272// remove the first element273private void removeFirst(final List<Integer> original, final List<Integer> list, final AtomicInteger offset) {274final AtomicBoolean first = new AtomicBoolean(true);275list.removeIf(x -> first.getAndSet(false));276CollectionAsserts.assertContents(original.subList(offset.getAndIncrement(), original.size()), list);277}278279@Test280public void testReplaceAll() {281final int scale = 3;282@SuppressWarnings("unchecked")283final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);284for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {285final List<Integer> original = test.expected;286final List<Integer> list = test.collection;287288try {289list.replaceAll(null);290fail("expected NPE not thrown");291} catch (NullPointerException npe) {}292CollectionAsserts.assertContents(list, original);293294list.replaceAll(x -> scale * x);295for (int i = 0; i < original.size(); i++) {296assertTrue(list.get(i) == (scale * original.get(i)), "mismatch at index " + i);297}298299if (original.size() > SUBLIST_SIZE) {300final List<Integer> subList = list.subList(SUBLIST_FROM, SUBLIST_TO);301subList.replaceAll(x -> x + 1);302// verify elements in view [from, to) were replaced303for (int i = 0; i < SUBLIST_SIZE; i++) {304assertTrue(subList.get(i) == ((scale * original.get(i + SUBLIST_FROM)) + 1),305"mismatch at sublist index " + i);306}307// verify that elements [0, from) remain unmodified308for (int i = 0; i < SUBLIST_FROM; i++) {309assertTrue(list.get(i) == (scale * original.get(i)),310"mismatch at original index " + i);311}312// verify that elements [to, size) remain unmodified313for (int i = SUBLIST_TO; i < list.size(); i++) {314assertTrue(list.get(i) == (scale * original.get(i)),315"mismatch at original index " + i);316}317}318}319320for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {321final List<Integer> list = test.collection;322trimmedSubList(list, l -> {323final List<Integer> copy = new ArrayList<>(l);324final int offset = 5;325l.replaceAll(x -> offset + x);326for (int i = 0; i < copy.size(); i++) {327assertTrue(l.get(i) == (offset + copy.get(i)), "mismatch at index " + i);328}329});330}331}332333@Test334public void testSort() {335@SuppressWarnings("unchecked")336final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);337for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {338final List<Integer> original = test.expected;339final List<Integer> list = test.collection;340CollectionSupplier.shuffle(list);341list.sort(Integer::compare);342CollectionAsserts.assertSorted(list, Integer::compare);343if (test.name.startsWith("reverse")) {344Collections.reverse(list);345}346CollectionAsserts.assertContents(list, original);347348CollectionSupplier.shuffle(list);349list.sort(null);350CollectionAsserts.assertSorted(list, Comparator.naturalOrder());351if (test.name.startsWith("reverse")) {352Collections.reverse(list);353}354CollectionAsserts.assertContents(list, original);355356CollectionSupplier.shuffle(list);357list.sort(Comparator.naturalOrder());358CollectionAsserts.assertSorted(list, Comparator.naturalOrder());359if (test.name.startsWith("reverse")) {360Collections.reverse(list);361}362CollectionAsserts.assertContents(list, original);363364CollectionSupplier.shuffle(list);365list.sort(Comparator.reverseOrder());366CollectionAsserts.assertSorted(list, Comparator.reverseOrder());367if (!test.name.startsWith("reverse")) {368Collections.reverse(list);369}370CollectionAsserts.assertContents(list, original);371372CollectionSupplier.shuffle(list);373list.sort(BIT_COUNT_COMPARATOR);374CollectionAsserts.assertSorted(list, BIT_COUNT_COMPARATOR);375// check sort by verifying that bitCount increases and never drops376int minBitCount = 0;377for (final Integer i : list) {378int bitCount = Integer.bitCount(i);379assertTrue(bitCount >= minBitCount);380minBitCount = bitCount;381}382383// Resuse the supplier to store AtomicInteger instead of Integer384// Hence the use of raw type and cast385List<AtomicInteger> incomparablesData = new ArrayList<>();386for (int i = 0; i < test.expected.size(); i++) {387incomparablesData.add(new AtomicInteger(i));388}389Function f = test.supplier;390@SuppressWarnings("unchecked")391List<AtomicInteger> incomparables = (List<AtomicInteger>) f.apply(incomparablesData);392393CollectionSupplier.shuffle(incomparables);394incomparables.sort(ATOMIC_INTEGER_COMPARATOR);395for (int i = 0; i < test.expected.size(); i++) {396assertEquals(i, incomparables.get(i).intValue());397}398399400if (original.size() > SUBLIST_SIZE) {401final List<Integer> copy = new ArrayList<>(list);402final List<Integer> subList = list.subList(SUBLIST_FROM, SUBLIST_TO);403CollectionSupplier.shuffle(subList);404subList.sort(Comparator.naturalOrder());405CollectionAsserts.assertSorted(subList, Comparator.naturalOrder());406// verify that elements [0, from) remain unmodified407for (int i = 0; i < SUBLIST_FROM; i++) {408assertTrue(list.get(i) == copy.get(i),409"mismatch at index " + i);410}411// verify that elements [to, size) remain unmodified412for (int i = SUBLIST_TO; i < list.size(); i++) {413assertTrue(list.get(i) == copy.get(i),414"mismatch at index " + i);415}416}417}418419for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {420final List<Integer> list = test.collection;421trimmedSubList(list, l -> {422CollectionSupplier.shuffle(l);423l.sort(Comparator.naturalOrder());424CollectionAsserts.assertSorted(l, Comparator.naturalOrder());425});426}427}428429@Test430public void testForEachThrowsCME() {431@SuppressWarnings("unchecked")432final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);433for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {434final List<Integer> list = test.collection;435436if (list.size() <= 1) {437continue;438}439boolean gotException = false;440try {441// bad predicate that modifies its list, should throw CME442list.forEach(list::add);443} catch (ConcurrentModificationException cme) {444gotException = true;445}446if (!gotException) {447fail("expected CME was not thrown from " + test);448}449}450}451452@Test453public void testRemoveIfThrowsCME() {454@SuppressWarnings("unchecked")455final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);456for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {457final List<Integer> list = test.collection;458459if (list.size() <= 1) {460continue;461}462boolean gotException = false;463try {464// bad predicate that modifies its list, should throw CME465list.removeIf(list::add);466} catch (ConcurrentModificationException cme) {467gotException = true;468}469if (!gotException) {470fail("expected CME was not thrown from " + test);471}472}473}474475@Test476public void testReplaceAllThrowsCME() {477@SuppressWarnings("unchecked")478final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);479for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {480final List<Integer> list = test.collection;481482if (list.size() <= 1) {483continue;484}485boolean gotException = false;486try {487// bad predicate that modifies its list, should throw CME488list.replaceAll(x -> {int n = 3 * x; list.add(n); return n;});489} catch (ConcurrentModificationException cme) {490gotException = true;491}492if (!gotException) {493fail("expected CME was not thrown from " + test);494}495}496}497498@Test499public void testSortThrowsCME() {500@SuppressWarnings("unchecked")501final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);502for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {503final List<Integer> list = test.collection;504505if (list.size() <= 1) {506continue;507}508boolean gotException = false;509try {510// bad predicate that modifies its list, should throw CME511list.sort((x, y) -> {list.add(x); return x - y;});512} catch (ConcurrentModificationException cme) {513gotException = true;514}515if (!gotException) {516fail("expected CME was not thrown from " + test);517}518}519}520521private static final List<Integer> SLICED_EXPECTED = Arrays.asList(0, 1, 2, 3, 5, 6, 7, 8, 9);522private static final List<Integer> SLICED_EXPECTED2 = Arrays.asList(0, 1, 2, 5, 6, 7, 8, 9);523524@DataProvider(name="shortIntListProvider", parallel=true)525public static Object[][] intListCases() {526final Integer[] DATA = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};527final List<Object[]> cases = new LinkedList<>();528cases.add(new Object[] { new ArrayList<>(Arrays.asList(DATA)) });529cases.add(new Object[] { new LinkedList<>(Arrays.asList(DATA)) });530cases.add(new Object[] { new Vector<>(Arrays.asList(DATA)) });531cases.add(new Object[] { new CopyOnWriteArrayList<>(Arrays.asList(DATA)) });532cases.add(new Object[] { new ExtendsAbstractList<>(Arrays.asList(DATA)) });533return cases.toArray(new Object[0][cases.size()]);534}535536@Test(dataProvider = "shortIntListProvider")537public void testRemoveIfFromSlice(final List<Integer> list) {538final List<Integer> sublist = list.subList(3, 6);539assertTrue(sublist.removeIf(x -> x == 4));540CollectionAsserts.assertContents(list, SLICED_EXPECTED);541542final List<Integer> sublist2 = list.subList(2, 5);543assertTrue(sublist2.removeIf(x -> x == 3));544CollectionAsserts.assertContents(list, SLICED_EXPECTED2);545}546}547548549