Closing a java.util.Iterator

前端 未结 7 1795
清酒与你
清酒与你 2020-12-29 02:32

I\'ve implemented a custom java.util.Iterator using a resource that should be released at the end using a close() method. That resource could

7条回答
  •  死守一世寂寞
    2020-12-29 03:22

    In your implementation you could close it your self, if when the iteratoror is exhausted.

    public boolean hasNext() {
           .... 
           if( !hasNext ) {
               this.close();
           }
           return hasNext;
     }
    

    And clearly document:

    This iterator will invoke close() when hasNext() return false, if you need to dispose the iterator before make sure you call close your self

    example:

    void testIt() {
         Iterator i = DbIterator.connect("db.config.info.here");
         try {
              while( i.hasNext() {
                  process( i.next() );
              }
          } finally {
              if( i != null )  {
                  i.close();
              }
          }
      }
    

    Btw, you could while you're there you could implement Iterable and use the enhanced for loop.

提交回复
热议问题