Next iterator method

There ResultSetis a method in the interface nextthat returns a boolean, and then you can directly access the current record using methodsget

Why Iteratorof java.utilsimply cast hasNext()method and is only a method next, which will move the cursor to the next element and returns boolean?

+5
source share
3 answers

Because it next()is currently returning the next element.

Java could implement an iterator pattern just like .NET does, with a MoveNext()boolean and then a property Currentwith the "current" value - but these are still two members ..

, " " " , " - Maybe. , Java , ...

+8

, .

ResultSet next() false, . getString(), getInt() - , . , :

while (rs.next())
{
  name=rs.getString("name"); // or whatever
  ... do something with name ...
}

Iterator hasNext() true false, , . next() . :

while (iter.hasnext())
{
  name=iter.next(); // or whatever
  ... do something with name ...
}

. , . ResultSet.next , , positoin, Iterator.hasNext , , . .

Iterator.hasNext Iterator.next . , ? , null ... , null ? , - , , . , ints, , -1 end-of-list, , -1?

, , , next() , , , , . . - :

while (true)
{
  IterableResult ir=iter.next();
  if (ir.end)
  {
    break;
  }
  else
  {
    name=ir.value;
    ... do something with name ... 
  }
}

-.

, , , . , , Iterator !: -)

+2

next() ResultSet hasNext() . ResultSet next() .

: ResultSet , , ? , , ResultSet java Iterator. ORM- , JDBC ResultSet.

JDK, .

0

All Articles