Friday, February 25, 2011

Java Iterator - Best practices


In a recent code review at WSO2, Afkham Azeez mentioned some java best practices. This was something I didn't knew before. There are two ways to use a java iterator. One method is using a While-loop. The other way is to use For-loop. But the first method can drive you into errors if not correctly handled. Look at the following code.
List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add("3");

Iterator<String> iter = list.iterator();
    while ( iter.hasNext() ){
      System.out.println( iter.next() );
    }

System.out.println(iter.next());

If you see carefully, now the iterator can been used outside the while-loop and it might throw NoSuchElementException as iter.hasNext() is not called, in each iter.next() call.

By using a for-loop we can avoid this by restricting the iterator to be accessed only inside the for-loop scope.

eg -
List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add("3");

for ( Iterator<String> iter = list.iterator(); iter.hasNext(); ) {
      System.out.println( iter.next() );
    }