Java Magazine, Nov/Dec 2017
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2017 98 fix this The other generally safe approach is that the Iterator and ListIterator interfaces define a remove method These methods are intended to be able to remove the most recently seen element from the structure being iterated The code in option C correctly uses this feature and therefore option C is correct However although the remove method and the style of its use in option C are generally correct the remove method is an optional operation because the underlying list might be immutable This means that option E is also correct In fact its the API documentation for the remove method of Iterator that tells you any other kind of modification is unsafe It says The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method Of course this notation doesnt entirely explain why options A and B should be unsafe The answer lies in the underlying mechanisms of the enhanced for loop and the forEach method As youve probably guessed by now they use the Iterator in their implementations Java Language Specification section 14142 describes how the enhanced for construction is translated into a regular for loop and the Iterator is extracted and used The API documentation for the Iterable forEach method similarly describes the likely implementation of the forEach behavior in terms of the Iterable Given this its clear that options A and B must also be incorrect Question 4 The correct answer is option D This question investigates the essential behavior of an Optional object An Optional allows you to avoid passing null pointers around and the associated need to test for them frequently Instead an Optional lets you pass a real object that wraps another object that might or might not exist The Optional allows you to avoid writing code like the following String s operationThatMightReturnNull An Optional lets you pass a real object that wraps another object that might or might not exist
You must have JavaScript enabled to view digital editions.