8292317: Missing null check for Iterator.forEachRemaining implementations

Reviewed-by: sundar, smarks
This commit is contained in:
Jaikiran Pai 2022-11-19 00:55:14 +00:00
parent 0ec575a203
commit 906f1ca4d7
2 changed files with 29 additions and 1 deletions
src/java.base/share/classes/java/util
test/jdk/java/util/Collections

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2022, 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
@ -1714,6 +1714,7 @@ public class Collections {
throw new UnsupportedOperationException();
}
public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
Objects.requireNonNull(action);
i.forEachRemaining(entryConsumer(action));
}
};
@ -3878,6 +3879,7 @@ public class Collections {
}
public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
Objects.requireNonNull(action);
i.forEachRemaining(
e -> action.accept(checkedEntry(e, valueType)));
}

@ -1,4 +1,5 @@
/*
* Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018 Google Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@ -195,4 +196,29 @@ public class DelegatingIteratorForEachRemaining {
Class clazz = entrySet.iterator().next().getClass();
assertThrowingIterator(Collections.checkedSet(entrySet, clazz).iterator());
}
/**
* Calls Collections.unmodifiableMap().entrySet().iterator().forEachRemaining() by passing
* that method a {@code null} action and expects that call to fail with a
* {@code NullPointerException}.
*/
@Test
public void testUnmodifiableForEachRemainingNPE() {
final Iterator<?> it = Collections.unmodifiableMap(Map.of()).entrySet().iterator();
// pass null action and expect a NPE
Assert.assertThrows(NullPointerException.class, () -> it.forEachRemaining(null));
}
/**
* Calls Collections.checkedMap().entrySet().iterator().forEachRemaining() by passing
* that method a {@code null} action and expects that call to fail with a
* {@code NullPointerException}.
*/
@Test
public void testCheckedMapForEachRemainingNPE() {
final Iterator<?> it = Collections.checkedMap(Map.of(), String.class,
String.class).entrySet().iterator();
// pass null "action" and expect it to fail with NPE
Assert.assertThrows(NullPointerException.class, () -> it.forEachRemaining(null));
}
}