YOUR FEEDBACK
Werner Keil wrote: Java 6 update 10. If I'd be running Apple, I'd probably really drop dead...
AJAXWorld RIA Conference
$300 Savings Expire September 12th. Register Today and SAVE!


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP LINKS YOU MUST CLICK ON


Java Developer's Journal: "Developing in Java 5"
How to use the new set of tools wisely

"Ease of Development" is one of the main focuses in J2SE 5. Accordingly, J2SE 5 introduces several new features designed to simplify the developer's life. If you use these new constructs, your code will become more compact and expressive, hence easier to understand and debug. This article explains how you can use the new features to prevent some silly mistakes, as well as some that are not so silly.

Generics
The Collections framework was introduced in Java 1.2. It provides a set of interfaces and implementations that encapsulate many common data structures, the most common being the List and Map interfaces.

The main drawback of using this well-thought-out framework is that a significant amount of casting is required when extracting elements from a pre-J2SE 5 collection (because the collection necessarily has no knowledge of what kind of elements are stored in it). Listing 1 provides a simple example. In the listing, the line with the cast is clunky. Yet it seems that nothing could go wrong, since the only way to add elements to fileList is through the addFile method, which takes only a string.

However, problems will inevitably surface sooner or later. For instance, assume that two years later, you or another developer decide that it would be a good idea to store actual File objects (instead of their names) in the FileList class.

The addFile method will be changed to read:


public void addFile (File file) {
fileList.add(file);
}
The code will compile just fine. Yet, when the customer runs the application, it will crash with a ClassCastException as soon as the listExtensions () method is called. One way to guard against this problem is to wrap each casting operation into some defensive code:

while (it.hasNext()) {
Object name = it.next();
if (name instanceof String) {
System.out.println
(getExtension((String)name));
}
}
This will solve the immediate problem, but it has several drawbacks:
  • The code is now even clunkier (and, consequently, more difficult to maintain).
  • There are (potentially) many unnecessary instanceof operations.
  • The application will fail silently instead of crashing when a disruptive change in code (such as the one above) occurs. Whether this is a better or worse situation for the customer and the support staff is debatable.
I'm pretty sure that most developers wouldn't make such an obvious mistake, but the problem can manifest itself in much more subtle ways, and it grows into a major issue when libraries are shared across team and company boundaries.

J2SE 5 provides a solution for all of this: collections can now use generics. For instance:

private List <String> fileList = new ArrayList <String> ();

Now, only strings can be added to fileList, and method calls, such as fileList.get(0) and fileList.iterator().next(), will return strings with no casting necessary:

String name = it.next();

If you use generics and try to modify the addFile method, the compiler will flag your attempt to add a File to a List<String>. If you change the declaration of fileList to a List<File>, the compiler will now notice that it.next() returns File and not a string; this will force you to fix the listExtensions method.

Note that this is just one use of generics. One of my other favorites is that since the Comparable interface is now generic, you can write the following code and avoid the boilerplate instanceof/casting code that is common for compareTo method implementations:


public class Comp implements Comparable <Comp> {
public int compareTo(Comp o) {
....
}
}
Enhanced For Loop
Here is a snippet of buggy code (slightly modified from the J2SE 5 release notes):

List <Suit> suits = ...;
List <Rank> ranks = ...;
List <Card> sortedDeck = new ArrayList <Card> ();

for (Iterator <Suit> i = suits.iterator(); i.hasNext(); )
for (Iterator <Rank> j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(i.next(), j.next()));
If you try to run it, it will throw a NoSuchElementException. Can you spot the bug? The problem is that i.next() is being called every time a new card is created, rather than once per suit. As a result, we run out of suits much faster than expected. This is how to fix the loop:

for (Iterator <Suit> i = suits.iterator(); i.hasNext(); ) {
Suit suit = i.next();
for (Iterator <Rank> j = ranks.iterator(); j.hasNext(); )
Rank rank = j.next();
sortedDeck.add(new Card(suit, rank));
}
J2SE 5's new enhanced for loop construct provides a neat solution for this. The nested loop in the above code can be rewritten as:

for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
What appears to be happening is that the variables suit and rank point (in turn) to the elements of the Lists suits and ranks. Under the hood, the same code as in the fixed loop is being run.

Enhanced for loops can also be used while iterating through arrays. This time, instead of not having to explicitly iterate in your code, you can skip any references to the array indices:


String [] vowels = new String [] {"a", "e", "i", "o", "u"};

for (vowel : vowels) {
System.out.println(vowel.toUpperCase());
}
As well as being more compact and easy to understand, the enhanced for construct for arrays prevents common bugs, such as referring to the wrong index in nested loops:

boolean isVowel (char c) {
}
int vowel_count = 0;
for (int i = 0; i < words.length; i++) {
String word = words[i];
for (int j = 0; j < word.length(); j++) {
if (isVowel(word.charAt(i)) {
vowel_count++;
}
}
}
Enums
C has an enum construct, which in theory allows the developer to define an enumerated type, but in practice does little more than define a bunch of integer constants. In the pre-J2SE 5 world, the most common way to accomplish the same task was to mimic the way C works and write code like this:

public class Card {
// suits
public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;
// ranks
public static final int ACE = 1;
public static final int DEUCE = 2;
...
public static final int KING = 13; }
About Roberto Scaramuzzi
Roberto Scaramuzzi is a software engineer at Parasoft. He grew up professionally as a Perl developer, but is now also adept at Java and PHP. Roberto holds a PhD in mathematics.

YOUR FEEDBACK
Student Loan Consolidation wrote: Interseting but they don't seem to be offering consolidation anymore. Check out sites like: http://www.StudentLoanCosloidator.com and http://www.dl.ed.gov/ to get your loans consolidated
Zalika Tyson wrote: NextStudent does not deserve this No. 4 spot because they are fraudulent tricksters. I have applied for a loan in February this year and till now have not received the check despite being approved for the loan since March! They claim to have sent the check to me by mail three times ... each time I called to see where the check was and they had to issue a stop payment and reissue another check. Now on the 4th go around, I am being told that in spite of giving them my credit card information to have the 4th check expressed to me, they do not do express deliveries because "it's too much paperwork". Now they've sent the check to my school ... and they're not sure because they might have sent it to my school with my apartment number on the envelope! Each time I call I get a different response depending on who I speak with! And I'm still waiting. I swear they are operating out of someone's gar...
LATEST ECLIPSE STORIES . . .
Genuitec announced their expansion into “Strategic Member” status for the Eclipse Foundation. This highest level of Foundation membership ensures both financial and technological backing of the Eclipse platform, as well as increased influence on the platform's evolution through boa...
Furthering its dedication to providing Java developers productivity with choice, Oracle announced the Oracle Enterprise Pack for Eclipse, a new component of Oracle Fusion Middleware. This release marks the first free Eclipse 3.4 environment to support Oracle WebLogic Server 10g Release...
Aptana announced the acquisition of Pydev. The combination of Pydev with Aptana Studio, which is approaching 2.3 million downloads, will bring Aptana's excellence in AJAX development ease to the Python community and bring Python support to Aptana's product lines. The move further reinf...
Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be...
Red Hat CTO Brian Stevens, Citrix CTO Simon Crosby, Egenera CTO Pete Manca, Allen Stewart, Group Manager, Windows Virtualization at Microsoft, and Brian Duckering, Sr. Director of Products and Alliances at Symantec were the top industry executives who joined Jeremy Geelan in the 4th Fl...
Genuitec announced the availability of MyEclipse Enterprise Workbench 7.0 milestone 1. This milestone release delivers advanced AJAX tooling for Java EE and full Application Lifecycle Management (ALM) capabilities for Eclipse 3.4 Ganymede, among other enhancements.
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE