picture home | pixelblog | qt_tools

omino code blog

We need code. Lots of code.
David Van Brink // Tue 2008.05.27 16:46 // {code java}

Java Gotcha

I was working on some code, and finding that it broke a bunch of unit tests. By the advanced method of “commenting out the new stuff”, I found that the line in red below appeared to be causing the problem.

If I commented out the line in red, everything worked! Put it back in, it all breaks!

for(IDocumentUrl doc : docs)
{
	@SuppressWarnings("unused") AltNode docUrlNode = new AltNode(DOCUMENT_URL);
//	docUrlNode.setValue(DISPLAY_NAME,doc.getTitle());
//	docUrlNode.setValue(TYPE,doc.getType().name());
//	docUrlNode.setValue(URL,doc.getUrl());
//	cardNode.addChild(docUrlNode);
}

What’s the deal?

The line in red is just allocating a harmless object. In fact… I replaced it with:

for(IDocumentUrl doc : docs)
{
	@SuppressWarnings("unused") Integer x = 3;
}

With the same symptoms. Comment out the line in red, and all is well.

Ah. Java does do some optimization! Removing the contents of the iterator loop allowed Java to omit the entire loop. Turns out docs was null; removing the contents of the iterator loop avoided an exception.

All fixed:

if(docs != null)
  for(IDocumentUrl doc : docs)
  {
    @SuppressWarnings("unused") AltNode docUrlNode = new AltNode(DOCUMENT_URL);
    docUrlNode.setValue(DISPLAY_NAME,doc.getTitle());
    docUrlNode.setValue(TYPE,doc.getType().name());
    docUrlNode.setValue(URL,doc.getUrl());
    cardNode.addChild(docUrlNode);
  }
oh, i dont know. what do you think?



(c) 2003-2011 omino.com / contact poly@omino.com