Is there any reason to avoid the timezone pattern in Java?

I heard that people are advised to always use the iterator pattern to control the loops instead of throwing an exception (as it is made in Python Iterators ) or using the Sentinel pattern , which returns a special, sentinel value (often null) indicating the end of the iteration.

Does best practice recommend against sentinel pattern? If so, why? (except that it does not work with syntax foreachin Java 1.5).

Edit: Code Example 1 - Sentinel Template

Reader r = ...;
for( int val = r.read(); val != -1; val = r.read()) {
   doSomethingWith(val);
}

Code Sample 2 - Iterator Pattern

for(Iterator<Thing> it = getAnIterator() ; it.hasNext(); ) {
  Thing t = it.next();
  doSomethingWith(t);
}
+5
source share
7

Sentinel , , . I.e., , , null .

+15

"" . - , .

, Java ( ) , , Java, , . , , , , .

+9

, , Iterator Java (, Iterable, ).

, Sentinel Java, - , -.

+4

Sentinel JDK , , . , . ( ). while , ​​ . .

, , , - .

+2

", , , ".

, , . :

for( int val = r.read(); val != -1; val = r.read()) {
   doSomethingWith(val);
}

" - -1, " " - -1, " " - -1, "? , hasNext .

, foreach map, ( ) , .

+2

, Sentinel , . , . , interator hasMore.

0

" " ". - , ".

, , " ", ""?

, , EOFExceptions ( , , -1 , , "-1 " ). , :

try {
    r = readNext(...);
    process(r);
} catch (EOFException e) {
    ...
}
0

All Articles