Tuesday, June 11, 2013

Java 1.5 Features

For/in loop

This is probably one of the coolest new features. I personally hate using iterators--it seems redundant and annoying sometimes. Well, lucky for me there's a way around them now!
So now you can do this:
for(Iterator lineup = list.iterator() ; lineup.hasNext() ; ) {
  Object thatThing = lineup.next();
  myMonster.eat(thatThing);
}
In a shortened:
for(Object thatThing : list) {
  myMonster.eat(thatThing);
}
Much prettier, no? This works with arrays too.
int[] nums = { 1, 2, 3, 4, 5, 6 };
 
for(int n : nums) {
  System.out.println(n);
}
Say you want to get your class to work with this nifty loop. Then, you have to implement Iterable (or extend something that does). This involves telling Iterable what type of things you iterate over. You can define a custom iterator to do something more robust, but for this illustration, I'm just going to grab one out of the list.
public class MailBox implements Iterable<MailMessage> {
  /** structure storing the messages */
  private ArrayList<MailMessage> messages;
 
  //...
 
  /**
   * Implemented for Iterable.
   */
  public Iterator<MailMessage>() {
    return messages.iterator();
  }
 
  //...
}

For more detailed information, see Java 1.5 Tiger: A Developer's Notebook[4] or the information on Sun's J2SE 5.0 language documentation.

Read to continue :  Java 1.5 Autoboxing/Unboxing

No comments:

Post a Comment