Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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() );
    }

Wednesday, March 11, 2009

How to convert an Java.Lang.String to w3c.dom.Element

Using javax.xml.parsers.DocumentBuilder class, an application programmer can obtain a org.w3c.dom.Document from XML.


This public org.w3c.dom.Document parse (InputStream is) has also other overloaded implementations for parsing a file; using the file name or the file objec(java.io.File)

Then you can retrieve the org.w3c.dom.Element by
    org.w3c.dom.Element e = doc.getDocumentElement();