java - Iterable: may iterator() returns null in case there is nothing to iterate over? -
an object implementing iterable
interface must have method signature:
iterator<t> iterator()
o being iterable
, code safe?
while(o.iterator().hasnext()) { ... }
in other terms, may iterator()
returns null in case there nothing iterate over?
edit:
1- of point out, iterator returned different each time o.iterator() executed. fair enough! must agree had forgotten point when writing question.
let's line rewritten:
iterator<string> = o.iterator(); .... .... while(it.hasnext() {...}
2- of point out, bad programming practice return null when documentation iterable.iterator() says: "returns iterator on set of elements of type t."
however question whether returning null prevented directly or indirectly 'contract' in java api documentation. me "returns iterator on set of elements of type t" doesn't prevent returning null. may wrong.
conclusion answers , additional research
overall: java api has no mean if iterator value may null or not, unless stating explicitly in documentation. in case, nothing stated, sense allows think null iterator value never returned java api methods. may different api written individuals.
- nothing in documentation prevents returned value null (e.g. @notnull)
- in javadoc, many @return explicit when null anticipated
- this question null return values in general, interesting.
- i've found an attempt language describe apis, though .net
may
iterator()
returnsnull
in case there nothing iterate over?
null
may returned (there no tools in java prevent doing it) it never should be. instead there should returned iterator hasnext
method should return false
immediately.
you need know purpose of iterable
objects used in for-each loop
for( type item : iterableinstance){ system.out.println(item); }
for(iterator<type> = somelist.iterator(); i.hasnext(); ) { type item = i.next(); system.out.println(item); }
so class method iterator()
return null
throw nullpointerexception
because of i.hasnext()
if instance empty make each time use for-each
catch npe
. not design , avoided returning instance of iterator
returns false
hasnext
stops loop.
also there other problem with
while(o.iterator().hasnext()) { ... }
approach. doing here each time condition checked new iterator created because calling o.iterator()
. in other words checking each time if first element exists, cause infinite loop if o
not empty.
what need
iterator<sometype> = o.iterator(); while(it.hasnext()) { ... }
Comments
Post a Comment