提交 d11eedbf 编写于 作者: M mduigou

7129185: Add Collections.{checked|empty|unmodifiable}Navigable{Map|Set}

Reviewed-by: dmocek, martin, smarks
上级 e5c1052c
...@@ -543,6 +543,8 @@ public abstract class AbstractMap<K,V> implements Map<K,V> { ...@@ -543,6 +543,8 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
/** /**
* Utility method for SimpleEntry and SimpleImmutableEntry. * Utility method for SimpleEntry and SimpleImmutableEntry.
* Test for equality, checking for nulls. * Test for equality, checking for nulls.
*
* NB: Do not replace with Object.equals until JDK-8015417 is resolved.
*/ */
private static boolean eq(Object o1, Object o2) { private static boolean eq(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2); return o1 == null ? o2 == null : o1.equals(o2);
......
...@@ -303,7 +303,7 @@ public interface NavigableSet<E> extends SortedSet<E> { ...@@ -303,7 +303,7 @@ public interface NavigableSet<E> extends SortedSet<E> {
* @throws ClassCastException {@inheritDoc} * @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc} * @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc}
na */ */
SortedSet<E> headSet(E toElement); SortedSet<E> headSet(E toElement);
/** /**
......
...@@ -71,6 +71,14 @@ public class MOAT { ...@@ -71,6 +71,14 @@ public class MOAT {
testCollection(new LinkedList<Integer>()); testCollection(new LinkedList<Integer>());
testCollection(new LinkedList<Integer>().subList(0,0)); testCollection(new LinkedList<Integer>().subList(0,0));
testCollection(new TreeSet<Integer>()); testCollection(new TreeSet<Integer>());
testCollection(Collections.checkedList(new ArrayList<Integer>(), Integer.class));
testCollection(Collections.synchronizedList(new ArrayList<Integer>()));
testCollection(Collections.checkedSet(new HashSet<Integer>(), Integer.class));
testCollection(Collections.checkedSortedSet(new TreeSet<Integer>(), Integer.class));
testCollection(Collections.checkedNavigableSet(new TreeSet<Integer>(), Integer.class));
testCollection(Collections.synchronizedSet(new HashSet<Integer>()));
testCollection(Collections.synchronizedSortedSet(new TreeSet<Integer>()));
testCollection(Collections.synchronizedNavigableSet(new TreeSet<Integer>()));
testCollection(new CopyOnWriteArrayList<Integer>()); testCollection(new CopyOnWriteArrayList<Integer>());
testCollection(new CopyOnWriteArrayList<Integer>().subList(0,0)); testCollection(new CopyOnWriteArrayList<Integer>().subList(0,0));
...@@ -98,6 +106,12 @@ public class MOAT { ...@@ -98,6 +106,12 @@ public class MOAT {
testMap(new Hashtable<Integer,Integer>()); testMap(new Hashtable<Integer,Integer>());
testMap(new ConcurrentHashMap<Integer,Integer>(10, 0.5f)); testMap(new ConcurrentHashMap<Integer,Integer>(10, 0.5f));
testMap(new ConcurrentSkipListMap<Integer,Integer>()); testMap(new ConcurrentSkipListMap<Integer,Integer>());
testMap(Collections.checkedMap(new HashMap<Integer,Integer>(), Integer.class, Integer.class));
testMap(Collections.checkedSortedMap(new TreeMap<Integer,Integer>(), Integer.class, Integer.class));
testMap(Collections.checkedNavigableMap(new TreeMap<Integer,Integer>(), Integer.class, Integer.class));
testMap(Collections.synchronizedMap(new HashMap<Integer,Integer>()));
testMap(Collections.synchronizedSortedMap(new TreeMap<Integer,Integer>()));
testMap(Collections.synchronizedNavigableMap(new TreeMap<Integer,Integer>()));
// Empty collections // Empty collections
final List<Integer> emptyArray = Arrays.asList(new Integer[]{}); final List<Integer> emptyArray = Arrays.asList(new Integer[]{});
...@@ -117,19 +131,29 @@ public class MOAT { ...@@ -117,19 +131,29 @@ public class MOAT {
testCollection(emptySet); testCollection(emptySet);
testEmptySet(emptySet); testEmptySet(emptySet);
testEmptySet(EMPTY_SET); testEmptySet(EMPTY_SET);
testEmptySet(Collections.emptySet());
testEmptySet(Collections.emptySortedSet());
testEmptySet(Collections.emptyNavigableSet());
testImmutableSet(emptySet); testImmutableSet(emptySet);
List<Integer> emptyList = emptyList(); List<Integer> emptyList = emptyList();
testCollection(emptyList); testCollection(emptyList);
testEmptyList(emptyList); testEmptyList(emptyList);
testEmptyList(EMPTY_LIST); testEmptyList(EMPTY_LIST);
testEmptyList(Collections.emptyList());
testImmutableList(emptyList); testImmutableList(emptyList);
Map<Integer,Integer> emptyMap = emptyMap(); Map<Integer,Integer> emptyMap = emptyMap();
testMap(emptyMap); testMap(emptyMap);
testEmptyMap(emptyMap); testEmptyMap(emptyMap);
testEmptyMap(EMPTY_MAP); testEmptyMap(EMPTY_MAP);
testEmptyMap(Collections.emptyMap());
testEmptyMap(Collections.emptySortedMap());
testEmptyMap(Collections.emptyNavigableMap());
testImmutableMap(emptyMap); testImmutableMap(emptyMap);
testImmutableMap(Collections.emptyMap());
testImmutableMap(Collections.emptySortedMap());
testImmutableMap(Collections.emptyNavigableMap());
// Singleton collections // Singleton collections
Set<Integer> singletonSet = singleton(1); Set<Integer> singletonSet = singleton(1);
......
...@@ -24,59 +24,42 @@ ...@@ -24,59 +24,42 @@
/* /*
* @test * @test
* @bug 6585904 * @bug 6585904
* @run testng CheckedIdentityMap
* @summary Checked collections with underlying maps with identity comparisons * @summary Checked collections with underlying maps with identity comparisons
*/ */
import java.util.*; import java.util.*;
import static java.util.Collections.*; import static java.util.Collections.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import org.testng.annotations.Test;
public class CheckedIdentityMap { public class CheckedIdentityMap {
void test(String[] args) throws Throwable {
@Test
public void testHashCode() {
Map<Integer, Integer> m1 = checkedMap( Map<Integer, Integer> m1 = checkedMap(
new IdentityHashMap<Integer, Integer>(), new IdentityHashMap<Integer, Integer>(),
Integer.class, Integer.class); Integer.class, Integer.class);
Map<Integer, Integer> m2 = checkedMap( Map<Integer, Integer> m2 = checkedMap(
new IdentityHashMap<Integer, Integer>(), new IdentityHashMap<Integer, Integer>(),
Integer.class, Integer.class); Integer.class, Integer.class);
// NB: these are unique instances. Compare vs. Integer.valueOf(1)
m1.put(new Integer(1), new Integer(1)); m1.put(new Integer(1), new Integer(1));
m2.put(new Integer(1), new Integer(1)); m2.put(new Integer(1), new Integer(1));
Map.Entry<Integer, Integer> e1 = m1.entrySet().iterator().next(); Map.Entry<Integer, Integer> e1 = m1.entrySet().iterator().next();
Map.Entry<Integer, Integer> e2 = m2.entrySet().iterator().next(); Map.Entry<Integer, Integer> e2 = m2.entrySet().iterator().next();
check(! e1.equals(e2));
check(e1.hashCode() == hashCode(e1)); assertNotEquals(e1, e2);
check(e2.hashCode() == hashCode(e2)); assertEquals(e1.hashCode(), hashCode(e1));
assertEquals(e2.hashCode(), hashCode(e2));
} }
int hashCode(Map.Entry<?,?> e) { static int hashCode(Map.Entry<?,?> e) {
return (System.identityHashCode(e.getKey()) ^ return (System.identityHashCode(e.getKey()) ^
System.identityHashCode(e.getValue())); System.identityHashCode(e.getValue()));
} }
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new CheckedIdentityMap().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
abstract class F {abstract void f() throws Throwable;}
void THROWS(Class<? extends Throwable> k, F... fs) {
for (F f : fs)
try {f.f(); fail("Expected " + k.getName() + " not thrown");}
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
Thread checkedThread(final Runnable r) {
return new Thread() {public void run() {
try {r.run();} catch (Throwable t) {unexpected(t);}}};}
} }
...@@ -23,24 +23,29 @@ ...@@ -23,24 +23,29 @@
/* /*
* @test * @test
* @bug 4904067 5023830 * @bug 4904067 5023830 7129185
* @summary Unit test for Collections.checkedMap * @summary Unit test for Collections.checkedMap
* @author Josh Bloch * @author Josh Bloch
* @run testng CheckedMapBash
*/ */
import java.util.*; import java.util.*;
import java.util.function.Supplier;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
public class CheckedMapBash { import static org.testng.Assert.fail;
static Random rnd = new Random(); import static org.testng.Assert.assertTrue;
static Object nil = new Integer(0);
public static void main(String[] args) {
int numItr = 100;
int mapSize = 100;
// Linked List test public class CheckedMapBash {
for (int i=0; i<numItr; i++) { static final Random rnd = new Random();
Map m = newMap(); static final Object nil = new Integer(0);
static final int numItr = 100;
static final int mapSize = 100;
@Test(dataProvider = "Bash.Supplier<Map<Integer,Integer>>")
public static void testCheckedMap(String description, Supplier<Map<Integer,Integer>> supplier) {
Map m = supplier.get();
Object head = nil; Object head = nil;
for (int j=0; j<mapSize; j++) { for (int j=0; j<mapSize; j++) {
...@@ -70,7 +75,7 @@ public class CheckedMapBash { ...@@ -70,7 +75,7 @@ public class CheckedMapBash {
fail("Incorrect equals computation."); fail("Incorrect equals computation.");
} }
Map m2 = newMap(); m2.putAll(m); Map m2 = supplier.get(); m2.putAll(m);
m2.values().removeAll(m.keySet()); m2.values().removeAll(m.keySet());
if (m2.size()!= 1 || !m2.containsValue(nil)) if (m2.size()!= 1 || !m2.containsValue(nil))
fail("Collection views test failed."); fail("Collection views test failed.");
...@@ -92,7 +97,9 @@ public class CheckedMapBash { ...@@ -92,7 +97,9 @@ public class CheckedMapBash {
fail("Linked list size not as expected."); fail("Linked list size not as expected.");
} }
Map m = newMap(); @Test(dataProvider = "Supplier<Map<Integer,Integer>>")
public static void testCheckeMap2(String description, Supplier<Map<Integer,Integer>> supplier) {
Map m = supplier.get();
for (int i=0; i<mapSize; i++) for (int i=0; i<mapSize; i++)
if (m.put(new Integer(i), new Integer(2*i)) != null) if (m.put(new Integer(i), new Integer(2*i)) != null)
fail("put returns a non-null value erroenously."); fail("put returns a non-null value erroenously.");
...@@ -101,7 +108,7 @@ public class CheckedMapBash { ...@@ -101,7 +108,7 @@ public class CheckedMapBash {
fail("contains value "+i); fail("contains value "+i);
if (m.put(nil, nil) == null) if (m.put(nil, nil) == null)
fail("put returns a null value erroenously."); fail("put returns a null value erroenously.");
Map m2 = newMap(); m2.putAll(m); Map m2 = supplier.get(); m2.putAll(m);
if (!m.equals(m2)) if (!m.equals(m2))
fail("Clone not equal to original. (1)"); fail("Clone not equal to original. (1)");
if (!m2.equals(m)) if (!m2.equals(m))
...@@ -134,16 +141,36 @@ public class CheckedMapBash { ...@@ -134,16 +141,36 @@ public class CheckedMapBash {
fail("Iterator.remove() failed"); fail("Iterator.remove() failed");
} }
static Map newMap() {
Map m = Collections.checkedMap(new HashMap(),
Integer.class, Integer.class);
if (!m.isEmpty()) @DataProvider(name = "Bash.Supplier<Map<Integer,Integer>>", parallel = true)
fail("New instance non empty."); public static Iterator<Object[]> bashNavigableMapProvider() {
return m; ArrayList<Object[]> iters = new ArrayList<>(makeCheckedMaps());
iters.ensureCapacity(numItr * iters.size());
for(int each=1; each < numItr; each++) {
iters.addAll( makeCheckedMaps());
}
return iters.iterator();
}
@DataProvider(name = "Supplier<Map<Integer,Integer>>", parallel = true)
public static Iterator<Object[]> navigableMapProvider() {
return makeCheckedMaps().iterator();
} }
static void fail(String s) { public static Collection<Object[]> makeCheckedMaps() {
throw new RuntimeException(s); return Arrays.asList(
new Object[]{"Collections.checkedMap(HashMap)",
(Supplier) () -> {return Collections.checkedMap(new HashMap(), Integer.class, Integer.class);}},
new Object[]{"Collections.checkedMap(TreeSet(reverseOrder)",
(Supplier) () -> {return Collections.checkedMap(new TreeMap(Collections.reverseOrder()), Integer.class, Integer.class);}},
new Object[]{"Collections.checkedMap(TreeSet).descendingSet()",
(Supplier) () -> {return Collections.checkedMap(new TreeMap().descendingMap(), Integer.class, Integer.class);}},
new Object[]{"Collections.checkedNavigableMap(TreeSet)",
(Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class);}},
new Object[]{"Collections.checkedNavigableMap(TreeSet(reverseOrder)",
(Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap(Collections.reverseOrder()), Integer.class, Integer.class);}},
new Object[]{"Collections.checkedNavigableMap().descendingSet()",
(Supplier) () -> {return Collections.checkedNavigableMap(new TreeMap().descendingMap(), Integer.class, Integer.class);}}
);
} }
} }
...@@ -23,32 +23,44 @@ ...@@ -23,32 +23,44 @@
/* /*
* @test * @test
* @bug 4904067 * @bug 4904067 7129185
* @summary Unit test for Collections.checkedSet * @summary Unit test for Collections.checkedSet
* @author Josh Bloch * @author Josh Bloch
* @run testng CheckedSetBash
*/ */
import java.util.*; import java.util.*;
import java.util.function.Supplier;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertTrue;
public class CheckedSetBash { public class CheckedSetBash {
static Random rnd = new Random(); static final int numItr = 100;
static final int setSize = 100;
static final Random rnd = new Random();
@Test(dataProvider = "Supplier<Set<Integer>>")
public static void testCheckedSet(String description, Supplier<Set<Integer>> supplier) {
public static void main(String[] args) { Set<Integer> s1 = supplier.get();
int numItr = 100; assertTrue(s1.isEmpty());
int setSize = 100;
for (int i=0; i<numItr; i++) {
Set s1 = newSet();
AddRandoms(s1, setSize); AddRandoms(s1, setSize);
Set s2 = newSet(); Set<Integer> s2 = supplier.get();
assertTrue(s2.isEmpty());
AddRandoms(s2, setSize); AddRandoms(s2, setSize);
Set intersection = clone(s1); Set<Integer> intersection = clone(s1, supplier);
intersection.retainAll(s2); intersection.retainAll(s2);
Set diff1 = clone(s1); diff1.removeAll(s2); Set<Integer> diff1 = clone(s1, supplier); diff1.removeAll(s2);
Set diff2 = clone(s2); diff2.removeAll(s1); Set<Integer> diff2 = clone(s2, supplier); diff2.removeAll(s1);
Set union = clone(s1); union.addAll(s2); Set<Integer> union = clone(s1, supplier); union.addAll(s2);
if (diff1.removeAll(diff2)) if (diff1.removeAll(diff2))
fail("Set algebra identity 2 failed"); fail("Set algebra identity 2 failed");
...@@ -93,12 +105,11 @@ public class CheckedSetBash { ...@@ -93,12 +105,11 @@ public class CheckedSetBash {
if (!s1.isEmpty()) if (!s1.isEmpty())
fail("Set nonempty after clear."); fail("Set nonempty after clear.");
} }
}
// Done inefficiently so as to exercise toArray // Done inefficiently so as to exercise toArray
static Set clone(Set s) { static <T> Set<T> clone(Set<T> s, Supplier<Set<T>> supplier) {
Set clone = newSet(); Set<T> clone = supplier.get();
List arrayList = Arrays.asList(s.toArray()); List<T> arrayList = Arrays.asList((T[]) s.toArray());
clone.addAll(arrayList); clone.addAll(arrayList);
if (!s.equals(clone)) if (!s.equals(clone))
fail("Set not equal to copy."); fail("Set not equal to copy.");
...@@ -109,13 +120,6 @@ public class CheckedSetBash { ...@@ -109,13 +120,6 @@ public class CheckedSetBash {
return clone; return clone;
} }
static Set newSet() {
Set s = Collections.checkedSet(new HashSet(), Integer.class);
if (!s.isEmpty())
fail("New instance non empty.");
return s;
}
static void AddRandoms(Set s, int n) { static void AddRandoms(Set s, int n) {
for (int i=0; i<n; i++) { for (int i=0; i<n; i++) {
int r = rnd.nextInt() % n; int r = rnd.nextInt() % n;
...@@ -136,8 +140,30 @@ public class CheckedSetBash { ...@@ -136,8 +140,30 @@ public class CheckedSetBash {
} }
} }
static void fail(String s) { @DataProvider(name = "Supplier<Set<Integer>>", parallel = true)
throw new RuntimeException(s); public static Iterator<Object[]> navigableSetsProvider() {
ArrayList<Object[]> iters = new ArrayList<>(makeCheckedSets());
iters.ensureCapacity(numItr * iters.size());
for(int each=1; each < numItr; each++) {
iters.addAll( makeCheckedSets());
}
return iters.iterator();
}
public static Collection<Object[]> makeCheckedSets() {
return Arrays.asList(
new Object[]{"Collections.checkedSet(HashSet)",
(Supplier) () -> {return Collections.checkedSet(new HashSet(), Integer.class);}},
new Object[]{"Collections.checkedSet(TreeSet(reverseOrder)",
(Supplier) () -> {return Collections.checkedSet(new TreeSet(Collections.reverseOrder()), Integer.class);}},
new Object[]{"Collections.checkedSet(TreeSet).descendingSet()",
(Supplier) () -> {return Collections.checkedSet(new TreeSet().descendingSet(), Integer.class);}},
new Object[]{"Collections.checkedNavigableSet(TreeSet)",
(Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(), Integer.class);}},
new Object[]{"Collections.checkedNavigableSet(TreeSet(reverseOrder)",
(Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(Collections.reverseOrder()), Integer.class);}},
new Object[]{"Collections.checkedNavigableSet().descendingSet()",
(Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet().descendingSet(), Integer.class);}}
);
} }
} }
...@@ -23,13 +23,20 @@ ...@@ -23,13 +23,20 @@
/* /*
* @test * @test
* @bug 4684279 * @bug 4684279 7129185
* @summary Empty utility collections should be singletons * @summary Empty utility collections should be singletons
* @author Josh Bloch * @author Josh Bloch
* @run testng EmptyCollectionSerialization
*/ */
import java.util.*; import java.util.*;
import java.util.function.Supplier;
import java.io.*; import java.io.*;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertSame;
public class EmptyCollectionSerialization { public class EmptyCollectionSerialization {
private static Object patheticDeepCopy(Object o) throws Exception { private static Object patheticDeepCopy(Object o) throws Exception {
...@@ -45,16 +52,48 @@ public class EmptyCollectionSerialization { ...@@ -45,16 +52,48 @@ public class EmptyCollectionSerialization {
return ois.readObject(); return ois.readObject();
} }
private static boolean isSingleton(Object o) throws Exception { @Test(dataProvider="SerializableSingletons")
return patheticDeepCopy(o) == o; public static void serializableSingletons(String description, Supplier<Object> o) {
try {
Object singleton = o.get();
assertSame(o.get(), singleton, description + ": broken Supplier not returning singleton");
Object copy = patheticDeepCopy(singleton);
assertSame( copy, singleton, description + ": " +
copy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(copy)) +
" is not the singleton " +
singleton.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(singleton)));
} catch(Exception all) {
fail(description + ": Unexpected Exception", all);
}
}
@DataProvider(name = "SerializableSingletons", parallel = true)
public static Iterator<Object[]> navigableMapProvider() {
return makeSingletons().iterator();
} }
public static void main(String[] args) throws Exception { public static Collection<Object[]> makeSingletons() {
if (!isSingleton(Collections.EMPTY_SET)) return Arrays.asList(
throw new Exception("EMPTY_SET"); new Object[]{"Collections.EMPTY_LIST",
if (!isSingleton(Collections.EMPTY_LIST)) (Supplier) () -> {return Collections.EMPTY_LIST;}},
throw new Exception("EMPTY_LIST"); new Object[]{"Collections.EMPTY_MAP",
if (!isSingleton(Collections.EMPTY_MAP)) (Supplier) () -> {return Collections.EMPTY_MAP;}},
throw new Exception("EMPTY_MAP"); new Object[]{"Collections.EMPTY_SET",
(Supplier) () -> {return Collections.EMPTY_SET;}},
new Object[]{"Collections.singletonMap()",
(Supplier) () -> {return Collections.emptyList();}},
new Object[]{"Collections.emptyMap()",
(Supplier) () -> {return Collections.emptyMap();}},
new Object[]{"Collections.emptySet()",
(Supplier) () -> {return Collections.emptySet();}},
new Object[]{"Collections.emptySortedSet()",
(Supplier) () -> {return Collections.emptySortedSet();}},
new Object[]{"Collections.emptySortedMap()",
(Supplier) () -> {return Collections.emptySortedMap();}},
new Object[]{"Collections.emptyNavigableSet()",
(Supplier) () -> {return Collections.emptyNavigableSet();}},
new Object[]{"Collections.emptyNavigableMap()",
(Supplier) () -> {return Collections.emptyNavigableMap();}}
);
} }
} }
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4533691 7129185
* @summary Unit test for Collections.emptyNavigableMap
* @run testng EmptyNavigableMap
*/
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertSame;
public class EmptyNavigableMap {
public static <T> void assertInstance(T actual, Class<? extends T> expected) {
assertInstance(expected.isInstance(actual), null);
}
public static <T> void assertInstance(T actual, Class<? extends T> expected, String message) {
assertTrue(expected.isInstance(actual), ((null != message) ? message : "")
+ " " + (actual == null ? "<null>" : actual.getClass().getSimpleName()) + " != " + expected.getSimpleName() + ". ");
}
public static <T extends Throwable> void assertEmptyNavigableMap(Object obj) {
assertInstance(obj, NavigableMap.class);
assertTrue(((NavigableMap)obj).isEmpty() && (((NavigableMap)obj).size() == 0));
}
public static <T extends Throwable> void assertEmptyNavigableMap(Object obj, String message) {
assertInstance(obj, NavigableMap.class, message);
assertTrue(((NavigableMap)obj).isEmpty() && (((NavigableMap)obj).size() == 0),
((null != message) ? message : "") + " Not empty. ");
}
public interface Thrower<T extends Throwable> {
public void run() throws T;
}
public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable) {
assertThrows(thrower, throwable, null);
}
public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable, String message) {
Throwable result;
try {
thrower.run();
fail(((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
return;
} catch (Throwable caught) {
result = caught;
}
assertInstance(result, throwable, ((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
}
public static final boolean isDescending(SortedMap<?,?> set) {
if (null == set.comparator()) {
// natural order
return false;
}
if (Collections.reverseOrder() == set.comparator()) {
// reverse natural order.
return true;
}
if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
// it's a Collections.reverseOrder(Comparator).
return true;
}
throw new IllegalStateException("can't determine ordering for " + set);
}
/**
* Tests that the comparator is {@code null}.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testComparatorIsNull(String description, NavigableMap<?,?> navigableMap) {
Comparator comparator = navigableMap.comparator();
assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
}
/**
* Tests that contains requires Comparable
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testContainsRequiresComparable(String description, NavigableMap<?,?> navigableMap) {
assertThrows(() -> {
navigableMap.containsKey(new Object());
},
ClassCastException.class,
description + ": Compareable should be required");
}
/**
* Tests that the contains method returns {@code false}.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testContains(String description, NavigableMap<?,?> navigableMap) {
assertFalse(navigableMap.containsKey(new Integer(1)),
description + ": Should not contain any elements.");
assertFalse(navigableMap.containsValue(new Integer(1)),
description + ": Should not contain any elements.");
}
/**
* Tests that the containsAll method returns {@code false}.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testContainsAll(String description, NavigableMap<?,?> navigableMap) {
TreeMap treeMap = new TreeMap();
treeMap.put("1", 1);
treeMap.put("2", 2);
treeMap.put("3", 3);
assertFalse(navigableMap.equals(treeMap), "Should not contain any elements.");
}
/**
* Tests that the iterator is empty.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testEmptyIterator(String description, NavigableMap<?,?> navigableMap) {
assertFalse(navigableMap.keySet().iterator().hasNext(), "The iterator is not empty.");
assertFalse(navigableMap.values().iterator().hasNext(), "The iterator is not empty.");
assertFalse(navigableMap.entrySet().iterator().hasNext(), "The iterator is not empty.");
}
/**
* Tests that the set is empty.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testIsEmpty(String description, NavigableMap<?,?> navigableMap) {
assertTrue(navigableMap.isEmpty(), "The set is not empty.");
}
/**
* Tests the headMap() method.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testHeadMap(String description, NavigableMap navigableMap) {
assertThrows(
() -> { NavigableMap ss = navigableMap.headMap(null, false); },
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(
() -> { NavigableMap ss = navigableMap.headMap(new Object(), true); },
ClassCastException.class,
description + ": Must throw ClassCastException for non-Comparable element");
NavigableMap ss = navigableMap.headMap("1", false);
assertEmptyNavigableMap(ss, description + ": Returned value is not empty navigable set.");
}
/**
* Tests that the size is 0.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testSizeIsZero(String description, NavigableMap<?,?> navigableMap) {
assertTrue(0 == navigableMap.size(), "The size of the set is not 0.");
}
/**
* Tests the subMap() method.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testSubMap(String description, NavigableMap navigableMap) {
assertThrows(
() -> {
SortedMap ss = navigableMap.subMap(null, BigInteger.TEN);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(
() -> {
SortedMap ss = navigableMap.subMap(BigInteger.ZERO, null);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(
() -> {
SortedMap ss = navigableMap.subMap(null, null);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
Object obj1 = new Object();
Object obj2 = new Object();
assertThrows(
() -> {
SortedMap ss = navigableMap.subMap(obj1, BigInteger.TEN);
},
ClassCastException.class, description
+ ": Must throw ClassCastException for parameter which is not Comparable.");
assertThrows(
() -> {
SortedMap ss = navigableMap.subMap(BigInteger.ZERO, obj2);
},
ClassCastException.class, description
+ ": Must throw ClassCastException for parameter which is not Comparable.");
assertThrows(
() -> {
SortedMap ss = navigableMap.subMap(obj1, obj2);
},
ClassCastException.class, description
+ ": Must throw ClassCastException for parameter which is not Comparable.");
// minimal range
navigableMap.subMap(BigInteger.ZERO, false, BigInteger.ZERO, false);
navigableMap.subMap(BigInteger.ZERO, false, BigInteger.ZERO, true);
navigableMap.subMap(BigInteger.ZERO, true, BigInteger.ZERO, false);
navigableMap.subMap(BigInteger.ZERO, true, BigInteger.ZERO, true);
Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO;
Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
assertThrows(
() -> {
navigableMap.subMap(last, true, first, false);
},
IllegalArgumentException.class, description
+ ": Must throw IllegalArgumentException when fromElement is not less then then toElement.");
navigableMap.subMap(first, true, last, false);
}
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testSubMapRanges(String description, NavigableMap navigableMap) {
Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO;
Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
NavigableMap subMap = navigableMap.subMap(first, true, last, true);
// same subset
subMap.subMap(first, true, last, true);
// slightly smaller
NavigableMap ns = subMap.subMap(first, false, last, false);
// slight exapansion
assertThrows(() -> {
ns.subMap(first, true, last, true);
},
IllegalArgumentException.class,
description + ": Expansion should not be allowed");
// much smaller
subMap.subMap(first, false, BigInteger.ONE, false);
}
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testheadMapRanges(String description, NavigableMap navigableMap) {
NavigableMap subMap = navigableMap.headMap(BigInteger.ONE, true);
// same subset
subMap.headMap(BigInteger.ONE, true);
// slightly smaller
NavigableMap ns = subMap.headMap(BigInteger.ONE, false);
// slight exapansion
assertThrows(() -> {
ns.headMap(BigInteger.ONE, true);
},
IllegalArgumentException.class,
description + ": Expansion should not be allowed");
// much smaller
subMap.headMap(isDescending(subMap) ? BigInteger.TEN : BigInteger.ZERO, true);
}
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testTailMapRanges(String description, NavigableMap navigableMap) {
NavigableMap subMap = navigableMap.tailMap(BigInteger.ONE, true);
// same subset
subMap.tailMap(BigInteger.ONE, true);
// slightly smaller
NavigableMap ns = subMap.tailMap(BigInteger.ONE, false);
// slight exapansion
assertThrows(() -> {
ns.tailMap(BigInteger.ONE, true);
},
IllegalArgumentException.class,
description + ": Expansion should not be allowed");
// much smaller
subMap.tailMap(isDescending(subMap) ? BigInteger.ZERO : BigInteger.TEN, false);
}
/**
* Tests the tailMap() method.
*/
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testTailMap(String description, NavigableMap navigableMap) {
assertThrows(() -> {
navigableMap.tailMap(null);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(() -> {
navigableMap.tailMap(new Object());
}, ClassCastException.class);
NavigableMap ss = navigableMap.tailMap("1", true);
assertEmptyNavigableMap(ss, description + ": Returned value is not empty navigable set.");
}
@DataProvider(name = "NavigableMap<?,?>", parallel = true)
public static Iterator<Object[]> navigableMapsProvider() {
return makeNavigableMaps().iterator();
}
public static Collection<Object[]> makeNavigableMaps() {
return Arrays.asList(
new Object[]{"UnmodifiableNavigableMap(TreeMap)", Collections.unmodifiableNavigableMap(new TreeMap())},
new Object[]{"UnmodifiableNavigableMap(TreeMap.descendingMap()", Collections.unmodifiableNavigableMap(new TreeMap().descendingMap())},
new Object[]{"UnmodifiableNavigableMap(TreeMap.descendingMap().descendingMap()", Collections.unmodifiableNavigableMap(new TreeMap().descendingMap().descendingMap())},
new Object[]{"emptyNavigableMap()", Collections.emptyNavigableMap()},
new Object[]{"emptyNavigableMap().descendingMap()", Collections.emptyNavigableMap().descendingMap()},
new Object[]{"emptyNavigableMap().descendingMap().descendingMap()", Collections.emptyNavigableMap().descendingMap().descendingMap()}
);
}
}
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4533691 7129185
* @summary Unit test for Collections.emptyNavigableSet
* @run testng EmptyNavigableSet
*/
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertSame;
public class EmptyNavigableSet {
public static <T> void assertInstance(T actual, Class<? extends T> expected) {
assertInstance(expected.isInstance(actual), null);
}
public static <T> void assertInstance(T actual, Class<? extends T> expected, String message) {
assertTrue(expected.isInstance(actual), ((null != message) ? message : "")
+ " " + (actual == null ? "<null>" : actual.getClass().getSimpleName()) + " != " + expected.getSimpleName() + ". ");
}
public static <T extends Throwable> void assertEmptyNavigableSet(Object obj) {
assertInstance(obj, NavigableSet.class);
assertTrue(((NavigableSet)obj).isEmpty() && (((NavigableSet)obj).size() == 0));
}
public static <T extends Throwable> void assertEmptyNavigableSet(Object obj, String message) {
assertInstance(obj, NavigableSet.class, message);
assertTrue(((NavigableSet)obj).isEmpty() && (((NavigableSet)obj).size() == 0),
((null != message) ? message : "") + " Not empty. ");
}
public interface Thrower<T extends Throwable> {
public void run() throws T;
}
public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable) {
assertThrows(thrower, throwable, null);
}
public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable, String message) {
Throwable result;
try {
thrower.run();
fail(((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
return;
} catch (Throwable caught) {
result = caught;
}
assertInstance(result, throwable, ((null != message) ? message : "") + "Failed to throw " + throwable.getCanonicalName() + ". ");
}
public static final boolean isDescending(SortedSet<?> set) {
if (null == set.comparator()) {
// natural order
return false;
}
if (Collections.reverseOrder() == set.comparator()) {
// reverse natural order.
return true;
}
if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
// it's a Collections.reverseOrder(Comparator).
return true;
}
throw new IllegalStateException("can't determine ordering for " + set);
}
/**
* Tests that the comparator is {@code null}.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testComparatorIsNull(String description, NavigableSet<?> navigableSet) {
Comparator comparator = navigableSet.comparator();
assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
}
/**
* Tests that contains requires Comparable
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testContainsRequiresComparable(String description, NavigableSet<?> navigableSet) {
assertThrows(() -> {
navigableSet.contains(new Object());
},
ClassCastException.class,
description + ": Compareable should be required");
}
/**
* Tests that the contains method returns {@code false}.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testContains(String description, NavigableSet<?> navigableSet) {
assertFalse(navigableSet.contains(new Integer(1)),
description + ": Should not contain any elements.");
}
/**
* Tests that the containsAll method returns {@code false}.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testContainsAll(String description, NavigableSet<?> navigableSet) {
TreeSet treeSet = new TreeSet();
treeSet.add("1");
treeSet.add("2");
treeSet.add("3");
assertFalse(navigableSet.containsAll(treeSet), "Should not contain any elements.");
}
/**
* Tests that the iterator is empty.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testEmptyIterator(String description, NavigableSet<?> navigableSet) {
Iterator emptyIterator = navigableSet.iterator();
assertFalse((emptyIterator != null) && (emptyIterator.hasNext()),
"The iterator is not empty.");
}
/**
* Tests that the set is empty.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testIsEmpty(String description, NavigableSet<?> navigableSet) {
assertTrue(navigableSet.isEmpty(), "The set is not empty.");
}
/**
* Tests that the first() method throws NoSuchElementException
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testFirst(String description, NavigableSet<?> navigableSet) {
assertThrows(() -> {
navigableSet.first();
}, NoSuchElementException.class, description);
}
/**
* Tests the headSet() method.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testHeadSet(String description, NavigableSet navigableSet) {
assertThrows(
() -> { NavigableSet ns = navigableSet.headSet(null, false); },
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(
() -> { NavigableSet ns = navigableSet.headSet(new Object(), true); },
ClassCastException.class,
description + ": Must throw ClassCastException for non-Comparable element");
NavigableSet ns = navigableSet.headSet("1", false);
assertEmptyNavigableSet(ns, description + ": Returned value is not empty navigable set.");
}
/**
* Tests that the last() method throws NoSuchElementException
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testLast(String description, NavigableSet<?> navigableSet) {
assertThrows(() -> {
navigableSet.last();
}, NoSuchElementException.class, description);
}
/**
* Tests that the size is 0.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testSizeIsZero(String description, NavigableSet<?> navigableSet) {
assertTrue(0 == navigableSet.size(), "The size of the set is not 0.");
}
/**
* Tests the subSet() method.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testSubSet(String description, NavigableSet navigableSet) {
assertThrows(
() -> {
SortedSet ss = navigableSet.subSet(null, BigInteger.TEN);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(
() -> {
SortedSet ss = navigableSet.subSet(BigInteger.ZERO, null);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(
() -> {
SortedSet ss = navigableSet.subSet(null, null);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
Object obj1 = new Object();
Object obj2 = new Object();
assertThrows(
() -> {
SortedSet ss = navigableSet.subSet(obj1, BigInteger.TEN);
},
ClassCastException.class, description
+ ": Must throw ClassCastException for parameter which is not Comparable.");
assertThrows(
() -> {
SortedSet ss = navigableSet.subSet(BigInteger.ZERO, obj2);
},
ClassCastException.class, description
+ ": Must throw ClassCastException for parameter which is not Comparable.");
assertThrows(
() -> {
SortedSet ss = navigableSet.subSet(obj1, obj2);
},
ClassCastException.class, description
+ ": Must throw ClassCastException for parameter which is not Comparable.");
// minimal range
navigableSet.subSet(BigInteger.ZERO, false, BigInteger.ZERO, false);
navigableSet.subSet(BigInteger.ZERO, false, BigInteger.ZERO, true);
navigableSet.subSet(BigInteger.ZERO, true, BigInteger.ZERO, false);
navigableSet.subSet(BigInteger.ZERO, true, BigInteger.ZERO, true);
Object first = isDescending(navigableSet) ? BigInteger.TEN : BigInteger.ZERO;
Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
assertThrows(
() -> {
navigableSet.subSet(last, true, first, false);
},
IllegalArgumentException.class, description
+ ": Must throw IllegalArgumentException when fromElement is not less then then toElement.");
navigableSet.subSet(first, true, last, false);
}
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testSubSetRanges(String description, NavigableSet navigableSet) {
Object first = isDescending(navigableSet) ? BigInteger.TEN : BigInteger.ZERO;
Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;
NavigableSet subSet = navigableSet.subSet(first, true, last, true);
// same subset
subSet.subSet(first, true, last, true);
// slightly smaller
NavigableSet ns = subSet.subSet(first, false, last, false);
// slight exapansion
assertThrows(() -> {
ns.subSet(first, true, last, true);
},
IllegalArgumentException.class,
description + ": Expansion should not be allowed");
// much smaller
subSet.subSet(first, false, BigInteger.ONE, false);
}
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testheadSetRanges(String description, NavigableSet navigableSet) {
NavigableSet subSet = navigableSet.headSet(BigInteger.ONE, true);
// same subset
subSet.headSet(BigInteger.ONE, true);
// slightly smaller
NavigableSet ns = subSet.headSet(BigInteger.ONE, false);
// slight exapansion
assertThrows(() -> {
ns.headSet(BigInteger.ONE, true);
},
IllegalArgumentException.class,
description + ": Expansion should not be allowed");
// much smaller
subSet.headSet(isDescending(subSet) ? BigInteger.TEN : BigInteger.ZERO, true);
}
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testTailSetRanges(String description, NavigableSet navigableSet) {
NavigableSet subSet = navigableSet.tailSet(BigInteger.ONE, true);
// same subset
subSet.tailSet(BigInteger.ONE, true);
// slightly smaller
NavigableSet ns = subSet.tailSet(BigInteger.ONE, false);
// slight exapansion
assertThrows(() -> {
ns.tailSet(BigInteger.ONE, true);
},
IllegalArgumentException.class,
description + ": Expansion should not be allowed");
// much smaller
subSet.tailSet(isDescending(subSet) ? BigInteger.ZERO : BigInteger.TEN, false);
}
/**
* Tests the tailSet() method.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testTailSet(String description, NavigableSet navigableSet) {
assertThrows(() -> {
navigableSet.tailSet(null);
},
NullPointerException.class,
description + ": Must throw NullPointerException for null element");
assertThrows(() -> {
navigableSet.tailSet(new Object());
}, ClassCastException.class);
NavigableSet ss = navigableSet.tailSet("1", true);
assertEmptyNavigableSet(ss, description + ": Returned value is not empty navigable set.");
}
/**
* Tests that the array has a size of 0.
*/
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testToArray(String description, NavigableSet<?> navigableSet) {
Object[] emptyNavigableSetArray = navigableSet.toArray();
assertTrue(emptyNavigableSetArray.length == 0, "Returned non-empty Array.");
emptyNavigableSetArray = new Object[20];
Object[] result = navigableSet.toArray(emptyNavigableSetArray);
assertSame(emptyNavigableSetArray, result);
assertTrue(result[0] == null);
}
@DataProvider(name = "NavigableSet<?>", parallel = true)
public static Iterator<Object[]> navigableSetsProvider() {
return makeNavigableSets().iterator();
}
public static Collection<Object[]> makeNavigableSets() {
return Arrays.asList(
new Object[]{"UnmodifiableNavigableSet(TreeSet)", Collections.unmodifiableNavigableSet(new TreeSet())},
new Object[]{"UnmodifiableNavigableSet(TreeSet.descendingSet()", Collections.unmodifiableNavigableSet(new TreeSet().descendingSet())},
new Object[]{"UnmodifiableNavigableSet(TreeSet.descendingSet().descendingSet()", Collections.unmodifiableNavigableSet(new TreeSet().descendingSet().descendingSet())},
new Object[]{"emptyNavigableSet()", Collections.emptyNavigableSet()},
new Object[]{"emptyNavigableSet().descendingSet()", Collections.emptyNavigableSet().descendingSet()},
new Object[]{"emptyNavigableSet().descendingSet().descendingSet()", Collections.emptyNavigableSet().descendingSet().descendingSet()}
);
}
}
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4533691
* @summary Unit test for Collections.emptySortedSet
*/
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import java.util.TreeSet;
public class EmptySortedSet {
static int status = 0;
private static final String FAILED = " failed. ";
private static final String PERIOD = ".";
private final String thisClassName = this.getClass().getName();
public static void main(String[] args) throws Exception {
new EmptySortedSet();
}
public EmptySortedSet() throws Exception {
run();
}
/**
* Returns {@code true} if the {@link Object} passed in is an empty
* {@link SortedSet}.
*
* @param obj the object to test
* @return {@code true} if the {@link Object} is an empty {@link SortedSet}
* otherwise {@code false}.
*/
private boolean isEmptySortedSet(Object obj) {
boolean isEmptySortedSet = false;
// We determine if the object is an empty sorted set by testing if it's
// an instance of SortedSet, and if so, if it's empty. Currently the
// testing doesn't include checks of the other methods.
if (obj instanceof SortedSet) {
SortedSet ss = (SortedSet) obj;
if ((ss.isEmpty()) && (ss.size() == 0)) {
isEmptySortedSet = true;
}
}
return isEmptySortedSet;
}
private void run() throws Exception {
Method[] methods = this.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
String methodName = method.getName();
if (methodName.startsWith("test")) {
try {
Object obj = method.invoke(this, new Object[0]);
} catch(Exception e) {
throw new Exception(this.getClass().getName() + "." +
methodName + " test failed, test exception "
+ "follows\n" + e.getCause());
}
}
}
}
private void throwException(String methodName, String reason)
throws Exception
{
StringBuilder sb = new StringBuilder(thisClassName);
sb.append(PERIOD);
sb.append(methodName);
sb.append(FAILED);
sb.append(reason);
throw new Exception(sb.toString());
}
/**
*
*/
private void test00() throws Exception {
//throwException("test00", "This test has not been implemented yet.");
}
/**
* Tests that the comparator is {@code null}.
*/
private void testComparatorIsNull() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
Comparator comparator = sortedSet.comparator();
if (comparator != null) {
throwException("testComparatorIsNull", "Comparator is not null.");
}
}
/**
* Tests that the contains method returns {@code false}.
*/
private void testContains() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
if (sortedSet.contains(new Object())) {
throwException("testContains", "Should not contain any elements.");
}
}
/**
* Tests that the containsAll method returns {@code false}.
*/
private void testContainsAll() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
TreeSet treeSet = new TreeSet();
treeSet.add("1");
treeSet.add("2");
treeSet.add("3");
if (sortedSet.containsAll(treeSet)) {
throwException("testContainsAll",
"Should not contain any elements.");
}
}
/**
* Tests that the iterator is empty.
*/
private void testEmptyIterator() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
Iterator emptyIterator = sortedSet.iterator();
if ((emptyIterator != null) && (emptyIterator.hasNext())) {
throwException("testEmptyIterator", "The iterator is not empty.");
}
}
/**
* Tests that the set is empty.
*/
private void testIsEmpty() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
if ((sortedSet != null) && (!sortedSet.isEmpty())) {
throwException("testSizeIsZero", "The set is not empty.");
}
}
/**
* Tests that the first() method throws NoSuchElementException
*/
private void testFirst() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
try {
sortedSet.first();
throwException("testFirst",
"NoSuchElemenException was not thrown.");
} catch(NoSuchElementException nsee) {
// Do nothing
}
}
/**
* Tests the headSet() method.
*/
private void testHeadSet() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
SortedSet ss;
try {
ss = sortedSet.headSet(null);
throwException("testHeadSet",
"Must throw NullPointerException for null element");
} catch(NullPointerException npe) {
// Do nothing
}
try {
ss = sortedSet.headSet(new Object());
throwException("testHeadSet",
"Must throw ClassCastException for non-Comparable element");
} catch(ClassCastException cce) {
// Do nothing.
}
ss = sortedSet.headSet("1");
if ((ss == null) || !isEmptySortedSet(ss)) {
throwException("testHeadSet",
"Returned value is null or not an EmptySortedSet.");
}
}
/**
* Tests that the last() method throws NoSuchElementException
*/
private void testLast() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
try {
sortedSet.last();
throwException("testLast",
"NoSuchElemenException was not thrown.");
} catch(NoSuchElementException nsee) {
// Do nothing
}
}
/**
* Tests that the size is 0.
*/
private void testSizeIsZero() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
int size = sortedSet.size();
if (size > 0) {
throwException("testSizeIsZero",
"The size of the set is greater then 0.");
}
}
/**
* Tests the subSet() method.
*/
private void testSubSet() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
SortedSet ss = sortedSet.headSet("1");
try {
ss = sortedSet.subSet(null, BigInteger.TEN);
ss = sortedSet.subSet(BigInteger.ZERO, null);
ss = sortedSet.subSet(null, null);
throwException("testSubSet",
"Must throw NullPointerException for null element");
} catch(NullPointerException npe) {
// Do nothing
}
try {
Object obj1 = new Object();
Object obj2 = new Object();
ss = sortedSet.subSet(obj1, BigInteger.TEN);
ss = sortedSet.subSet(BigInteger.ZERO, obj2);
ss = sortedSet.subSet(obj1, obj2);
throwException("testSubSet",
"Must throw ClassCastException for parameter which is "
+ "not Comparable.");
} catch(ClassCastException cce) {
// Do nothing.
}
try {
ss = sortedSet.subSet(BigInteger.ZERO, BigInteger.ZERO);
ss = sortedSet.subSet(BigInteger.TEN, BigInteger.ZERO);
throwException("testSubSet",
"Must throw IllegalArgumentException when fromElement is "
+ "not less then then toElement.");
} catch(IllegalArgumentException iae) {
// Do nothing.
}
ss = sortedSet.subSet(BigInteger.ZERO, BigInteger.TEN);
if (!isEmptySortedSet(ss)) {
throw new Exception("Returned value is not empty sorted set.");
}
}
/**
* Tests the tailSet() method.
*/
private void testTailSet() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
SortedSet ss;
try {
ss = sortedSet.tailSet(null);
throwException("testTailSet",
"Must throw NullPointerException for null element");
} catch(NullPointerException npe) {
// Do nothing
}
try {
SortedSet ss2 = sortedSet.tailSet(new Object());
throwException("testTailSet",
"Must throw ClassCastException for non-Comparable element");
} catch(ClassCastException cce) {
// Do nothing.
}
ss = sortedSet.tailSet("1");
if ((ss == null) || !isEmptySortedSet(ss)) {
throwException("testTailSet",
"Returned value is null or not an EmptySortedSet.");
}
}
/**
* Tests that the array has a size of 0.
*/
private void testToArray() throws Exception {
SortedSet sortedSet = Collections.emptySortedSet();
Object[] emptySortedSetArray = sortedSet.toArray();
if ((emptySortedSetArray == null) || (emptySortedSetArray.length > 0)) {
throwException("testToArray",
"Returned null array or array with length > 0.");
}
String[] strings = new String[2];
strings[0] = "1";
strings[1] = "2";
emptySortedSetArray = sortedSet.toArray(strings);
if ((emptySortedSetArray == null) || (emptySortedSetArray[0] != null)) {
throwException("testToArray",
"Returned null array or array with length > 0.");
}
}
}
...@@ -100,7 +100,14 @@ public class LockStep { ...@@ -100,7 +100,14 @@ public class LockStep {
new Hashtable(16), new Hashtable(16),
new TreeMap(), new TreeMap(),
new ConcurrentHashMap(16), new ConcurrentHashMap(16),
new ConcurrentSkipListMap() }); new ConcurrentSkipListMap(),
Collections.checkedMap(new HashMap(16), Integer.class, Integer.class),
Collections.checkedSortedMap(new TreeMap(), Integer.class, Integer.class),
Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class),
Collections.synchronizedMap(new HashMap(16)),
Collections.synchronizedSortedMap(new TreeMap()),
Collections.synchronizedNavigableMap(new TreeMap())
});
for (int j = 0; j < 10; j++) for (int j = 0; j < 10; j++)
put(maps, r.nextInt(100), r.nextInt(100)); put(maps, r.nextInt(100), r.nextInt(100));
......
...@@ -55,11 +55,19 @@ public class LockStep { ...@@ -55,11 +55,19 @@ public class LockStep {
lockSteps(new TreeMap(), lockSteps(new TreeMap(),
new ConcurrentSkipListMap()); new ConcurrentSkipListMap());
lockSteps(new TreeMap(),
Collections.checkedNavigableMap(new TreeMap(), Integer.class, Integer.class));
lockSteps(new TreeMap(),
Collections.synchronizedNavigableMap(new TreeMap()));
lockSteps(new TreeMap(reverseOrder()), lockSteps(new TreeMap(reverseOrder()),
new ConcurrentSkipListMap(reverseOrder())); new ConcurrentSkipListMap(reverseOrder()));
lockSteps(new TreeSet(), lockSteps(new TreeSet(),
new ConcurrentSkipListSet()); new ConcurrentSkipListSet());
lockSteps(new TreeSet(),
Collections.checkedNavigableSet(new TreeSet(), Integer.class));
lockSteps(new TreeSet(),
Collections.synchronizedNavigableSet(new TreeSet()));
lockSteps(new TreeSet(reverseOrder()), lockSteps(new TreeSet(reverseOrder()),
new ConcurrentSkipListSet(reverseOrder())); new ConcurrentSkipListSet(reverseOrder()));
} }
...@@ -181,7 +189,15 @@ public class LockStep { ...@@ -181,7 +189,15 @@ public class LockStep {
testEmptyCollection(m.values()); testEmptyCollection(m.values());
} }
static final Random rnd = new Random(); static final Random rnd;
static {
// sufficiently random for this test
long seed = System.nanoTime();
System.out.println(LockStep.class.getCanonicalName() + ": Trial random seed: " + seed );
rnd = new Random(seed);
}
static void equalNext(final Iterator<?> it, Object expected) { static void equalNext(final Iterator<?> it, Object expected) {
if (maybe(2)) if (maybe(2))
...@@ -208,8 +224,15 @@ public class LockStep { ...@@ -208,8 +224,15 @@ public class LockStep {
check(s.descendingSet().descendingSet().comparator() == null); check(s.descendingSet().descendingSet().comparator() == null);
equal(s.isEmpty(), s.size() == 0); equal(s.isEmpty(), s.size() == 0);
equal2(s, s.descendingSet()); equal2(s, s.descendingSet());
if (maybe(4) && s instanceof Serializable) if (maybe(4) && s instanceof Serializable) {
try {
equal2(s, serialClone(s)); equal2(s, serialClone(s));
} catch(RuntimeException uhoh) {
if(!(uhoh.getCause() instanceof NotSerializableException)) {
throw uhoh;
}
}
}
Comparator cmp = comparator(s); Comparator cmp = comparator(s);
if (s.isEmpty()) { if (s.isEmpty()) {
THROWS(NoSuchElementException.class, THROWS(NoSuchElementException.class,
...@@ -276,6 +299,15 @@ public class LockStep { ...@@ -276,6 +299,15 @@ public class LockStep {
check(! it2.hasNext()); check(! it2.hasNext());
} }
static void equalSetsLeaf(final Set s1, final Set s2) {
equal2(s1, s2);
equal( s1.size(), s2.size());
equal( s1.isEmpty(), s2.isEmpty());
equal( s1.hashCode(), s2.hashCode());
equal( s1.toString(), s2.toString());
equal( s1.containsAll(s2), s2.containsAll(s1));
}
static void equalNavigableSetsLeaf(final NavigableSet s1, static void equalNavigableSetsLeaf(final NavigableSet s1,
final NavigableSet s2) { final NavigableSet s2) {
equal2(s1, s2); equal2(s1, s2);
...@@ -448,8 +480,7 @@ public class LockStep { ...@@ -448,8 +480,7 @@ public class LockStep {
static void equalNavigableMaps(NavigableMap m1, static void equalNavigableMaps(NavigableMap m1,
NavigableMap m2) { NavigableMap m2) {
equalNavigableMapsLeaf(m1, m2); equalNavigableMapsLeaf(m1, m2);
equalNavigableSetsLeaf((NavigableSet) m1.keySet(), equalSetsLeaf(m1.keySet(), m2.keySet());
(NavigableSet) m2.keySet());
equalNavigableSets(m1.navigableKeySet(), equalNavigableSets(m1.navigableKeySet(),
m2.navigableKeySet()); m2.navigableKeySet());
equalNavigableSets(m1.descendingKeySet(), equalNavigableSets(m1.descendingKeySet(),
...@@ -836,5 +867,7 @@ public class LockStep { ...@@ -836,5 +867,7 @@ public class LockStep {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static <T> T serialClone(T obj) { static <T> T serialClone(T obj) {
try { return (T) readObject(serializedForm(obj)); } try { return (T) readObject(serializedForm(obj)); }
catch (Exception e) { throw new RuntimeException(e); }} catch (Error|RuntimeException e) { throw e; }
catch (Throwable e) { throw new RuntimeException(e); }
}
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册