Five favorite features in Java 5

Discussions

News: Five favorite features in Java 5

  1. Five favorite features in Java 5 (28 messages)

    David Flanagan has written up his five favorite things in Java 5, including:

    • Callable and Future interfaces
    • varargs and autoboxing
    • the Iterable, Appendable, Readable, Closeable, and Flushable interfaces
    • the @Override annotation
    • MatchResult

    He follows that up with some exposure to hexadecimal literals in Java 5, as an exposure to something obscure in the language.

    What are your five favorite features? Where can you see the features being leveraged? When do you think the new JVM will be widely used in J2EE?

    Threaded Messages (28)

  2. Interesting thanks. I must admit the Hex floating point literals are rather fun, a bit like the good ol'days with C on IEEE floating point stuff. Not exactly the best part of Java but curious all the same. I think my favourite new feature in the JVM has to be JMX.

    -John-
  3. Five favorite features in Java 5[ Go to top ]

    Interesting thanks. I must admit the Hex floating point literals are rather fun, a bit like the good ol'days with C on IEEE floating point stuff. Not exactly the best part of Java but curious all the same. I think my favourite new feature in the JVM has to be JMX.-John-

    +1 for JMX and JConsole... cool stuff that's finally pre-packaged.

    I'm looking forward to playing with Futures, too, but we've just switched this week to JDK5 (I know I'm 2 years behind Cedric's pre-alpha blog postings).
  4. A decimally number acting as a binary exponent for a hexidecimal base. Sweet, I'm gonna start using that one right away :p
  5. Sorry to become off topic, but the generics are in my optionion after having worked with 1.5 for several months now, the absolutely awful.
    They make the code much more verbose than the old explicit casting, there is no speed improvement since all the compiler does is only putting in casts, and the explicit inheritance declaration is sort of outright confusing.

    To become on topic again, I really love the foreach construct, that finally there is a non thread save StringBuffer version and autoboxing.
  6. We've standardized on Java 5 for our greenfield projects. There's a few nice features that I can think of:

       
    • System.nanoTime()
    •  
    • Formatters/Scanners
    •  
    • StringBuilders (drop-in unsynchronized replacement for StringBuffers)

    I would like to look at the Collections enhancements as soon as I can, looks like some good stuff in there.

    http://java.sun.com/j2se/1.5.0/docs/guide/collections/changes5.html
  7. Gotta be the generics...[ Go to top ]

    Knowing I can get a Foo out of i.next() instead of maybe a Bar makes life worth living.

    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
  8. Dsiagree a little[ Go to top ]

    Autboboxing is still evil. There's been plenty of evidence for that posted elsewhere.

    No mention of the enhanced for loop, but its evil too. What with no index available and hidden variables. They would've been better off providing a standard visitor-like method on java.util.Collection.

    It seems like both of these features were designed with quick'n'dirty in mind when in the long run, most cases I can think of would be better off with formal classes instead of these shortcuts, but once you have the shortcuts in place, it's harder to replace them.
  9. Autoboxing is evil...[ Go to top ]

    "Autoboxing is evil," so are cicular power saws, but I wouldn't try to build a house without one.

    Nuff Said.
  10. Dsiagree a little[ Go to top ]

    Autboboxing is still evil. There's been plenty of evidence for that posted elsewhere.
    And plenty of evidence of why it's not evil somewhere else.

    Personally, I haven't formed an opinion on it yet, having hardly used it so far.
    No mention of the enhanced for loop, but its evil too. What with no index available and hidden variables. They would've been better off providing a standard visitor-like method on java.util.Collection.

    That I disagree strongly with.

    Use the older loop if you need an index (which I sometimes do). We already have visitors and iterables, but what we didn't have was a short notation to express simple iterations, which probably represent 90% of all the loops out there.

    My code has become considerably easier to read ever since I switched my loops over to the new syntax, there is no way I would go back.

    Iterators are the real evil things (why do I need them if all I want is enumerate through the elements of an array or a list?!?).

    --
    Cedric
  11. Dsiagree a little[ Go to top ]

    You have to be careful of autoboxing and to some extent I don't like them either because of potential problems. For example, I've seen code like this:

    if (object.getLong() == 0) {
    ....
    }

    If originally the getLong() returned the basic type long then it is fine. However, if someone changes it to an Object Long the compiler sill still say it is ok. However, at runtime if getLong returns null then a null pointer exception is thrown.

    The enhanced for loop is great. Don't know why the original poster consider it Evil. If you want indicies etc then code it the old way.

    Dino
  12. Dsiagree a little[ Go to top ]

    Iterators are the real evil things (why do I need them if all I want is enumerate through the elements of an array or a list?!?).-- Cedric

    I think you are right. Enhanced for loop is only evil because Iterators are evil (I think you would still disgree on that point).

    Of course, I used such strong words to invoke a vibrant discussion. I haven't yet been able to work on a project with JDK 1.5, but I've found myself working around the lack of an enhanced for look quite easily!

    Instead of:

      Iterator i = things.iterator();r
      while(i.hasNext()) {
         painter.paint((Thing)i);
      }

    I prefer:

      things.visit(painter);

    The unfortunate part is that it requires me to use special collection subclasses or wrappers. But it does externalizes my painting from the iteration such that I caneasily refactor. I would've I preferred seeing JDK 1.5 include some syntax or API enhancements to allow writing constructs such as *those* easier, rather than the enhanced for loop. Enhanced for loop just makes my code *look* prettier while the design remains just as ugly as before.
  13. Dsiagree a little[ Go to top ]

    I prefer:  
    things.visit(painter)
    Visitor is a sophisticated pattern that you should only use for sophisticated problems.

    How about enumerating an array of strings? Visitors, iterators and even indexes seem overkill to me for this.

    for (String name : names) {
      System.out.println(name);
    }

    It doesn't get any cleaner that this.

    And here is a bonus question: can you tell the type of "names" is in the code above?

    You can't! And that's what's so great about the new for loop.

    --
    Cedric
  14. I can! I can![ Go to top ]

    for (String name : names) {
      System.out.println(name);
    }

    ...

    And here is a bonus question: can you tell the type of "names" is in the code above? You can't!

    Why, it's a java.lang.Iterable, of course!

    -Patrick

    --
    Patrick Linskey
    http://solarmetric.com
  15. I can! I can![ Go to top ]

    Why, it's a java.lang.Iterable, of course!

    How about:


    String[] names = {"x", "y", "z"};
    for (String name : names) {
       System.out.println(name);
    }
  16. I can! I can![ Go to top ]

    for (String name : names) {  System.out.println(name);}...And here is a bonus question: can you tell the type of "names" is in the code above? You can't!
    Why, it's a java.lang.Iterable, of course!

    But that's just "a" type, as opposed to "the" type ;-)

    Cedric wins on technical knock out. *gong*
  17. I can! I can![ Go to top ]

    Cedric wins on technical knock out. *gong*
    ADRIANNE!!!!
  18. Cleaner[ Go to top ]

    for (String name : names) {
      System.out.println(name);
    }
    It doesn't get any cleaner that this.
    It would be even more cleaner if they allowed in keyword instead of a cryptic ':'.
  19. InputStream[ Go to top ]

    It would be even more cleaner if they allowed in keyword instead of a cryptic ':'.
    I hope you realize that if they had used "in" as keyword it would have meant that a massive amount of code would have to be rewritten. "InputStream in=..." is veeeery common.

    Same thing goes for "enum" though I suppose.
  20. InputStream[ Go to top ]

    I hope you realize that if they had used "in" as keyword it would have meant that a massive amount of code would have to be rewritten. "InputStream in=..." is veeeery common.Same thing goes for "enum" though I suppose.

    It's worse than that, System.in makes impossible to maintain backwards compatibility with previous versions if they introduced an 'in' keyword. As far as I know, 'enum' was not used as a public identifier anywhere in the API.

    Dan.
  21. Re: InputStream[ Go to top ]

    While true, this is why the added the compile flag "-version" such as to avoid the enum dilemma.
  22. Dsiagree a little[ Go to top ]

    I prefer:  things.visit(painter)
    Visitor is a sophisticated pattern that you should only use for sophisticated problems.How about enumerating an array of strings? Visitors, iterators and even indexes seem overkill to me for this.for (String name : names) {  System.out.println(name);}It doesn't get any cleaner that this.And here is a bonus question: can you tell the type of "names" is in the code above?You can't! And that's what's so great about the new for loop.-- Cedric

    Do you really believe that's a good example. I mean, short of debug/test code, hwo often have you had to do that? More often, I'm displaying stuff in a web page or in a GUI where there are tags or components I must work through. I ultimately set such data in their model and let the rendering do its job.
  23. Dsiagree a little[ Go to top ]

    Do you really believe that's a good example. I mean, short of debug/test code, hwo often have you had to do that?
    Yes :-)

    I just picked a random class from one of my projects and here are some of the loops I found:

          List<XmlClass> testClassesFromXml = new ArrayList<XmlClass>();
          for (String className : m_classNames) {
            testClassesFromXml.add(new XmlClass(className));
          }

          for (ITestNGMethod m : tr.getBeforeSuiteMethods()) {
            beforeSuiteMethods.put(m, m);
          }

        for (TestRunner tr : m_testRunners) {
          invoker.invokeConfigurations(null, tr.getBeforeTestConfigurationMethods(),
              null /* instance */);

    Your mileage may vary of course, but what I notice in all the places where I use the new for loop is that using an index or an iterator would be useless and just clutter the code.

    --
    Cedric
  24. nested loops[ Go to top ]

    IMO, the new for loop syntax really shines in nested loops. Compare:

    for (Iterator iter = orders.iterator(); iter.hasNext(); ) {
    &nbsp;&nbsp;Order o = iter.next();
    &nbsp;&nbsp;for (Iterator iter2 = o.lineItems().iterator(); iter.hasNext(); ) {
    &nbsp;&nbsp;&nbsp;&nbsp;totalCost += iter2.next().price();
    &nbsp;&nbsp;}
    }

    for (Order o : orders) {
    &nbsp;&nbsp;for (LineItem i : o.lineItems()) {
    &nbsp;&nbsp;&nbsp;&nbsp;totalCost += i.price();
    &nbsp;&nbsp;}
    }

    Readability is a benefit here, but the significant benefit in my opinion is that the new syntax avoids the easy-to-overlook bug in the first example. Nested-loop bugs are a real difficulty, and something that can only be guarded against with good testing, or potentially an IDE that warns about the problem. FTR, of the three IDEs (emacs, vim, IntelliJ) that I use regularly, none of them give me any help on that first example.

    -Patrick

    --
    Patrick Linskey
    http://solarmetric.com
  25. nested loops[ Go to top ]

    Aargh, copy-and-paste. For those of you without HTML parsers in your heads, the code blocks are:

    for (Iterator iter = orders.iterator(); iter.hasNext(); ) {
      Order o = iter.next();
      for (Iterator iter2 = o.lineItems().iterator(); iter.hasNext(); ) {
        totalCost += iter2.next().price();
      }
    }

    for (Order o : orders) {
      for (LineItem i : o.lineItems()) {
        totalCost += i.price();
      }
    }

    -Patrick
  26. Visitors[ Go to top ]

    I agree that visitors are a pattern that should be used only when really needed. Don't fit your code to use a pattern. Use the pattern to achieve your goal.
    And it's rather easy to have a very generic visitor interface, which happens to evaluate each visit to a result,
    rather than assuming a void result from a visit (which you can do by making the second type parameter Void anyway)

    public interface Visitor <T, R> {
        public R visit(T obj);
    }

    And you can write a very short utility to iterate through any Collection, and return a List (I return a list here, so that you can tell the order in which the visitation occurred):

    public class VisitorUtil {

        public static <T, R> List<R> visitAll(Collection<T> collection, Visitor<T, R> visitor) {
            List<R> l = new ArrayList<R>();
            for (T t : collection) {
                l.add(visitor.visit(t));
            }
            return l;
        }
    }
  27. Dsiagree a little[ Go to top ]

    Iterators are the real evil things (why do I need them if all I want is enumerate through the elements of an array or a list?!?).-- Cedric
    I think you are right. Enhanced for loop is only evil because Iterators are evil (I think you would still disgree on that point).Of course, I used such strong words to invoke a vibrant discussion. I haven't yet been able to work on a project with JDK 1.5, but I've found myself working around the lack of an enhanced for look quite easily!Instead of:&nbsp;&nbsp;Iterator i = things.iterator();r&nbsp;&nbsp;while(i.hasNext()) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;painter.paint((Thing)i);&nbsp;&nbsp;}I prefer:&nbsp;&nbsp;things.visit(painter);The unfortunate part is that it requires me to use special collection subclasses or wrappers. But it does externalizes my painting from the iteration such that I caneasily refactor. I would've I preferred seeing JDK 1.5 include some syntax or API enhancements to allow writing constructs such as *those* easier, rather than the enhanced for loop. Enhanced for loop just makes my code *look* prettier while the design remains just as ugly as before.

    Why can't you just make your visit method take an Iterable, I don't see how this would require you do create any collection subclasses.

    Rob
    http://www.robsite.org
  28. Closeable should have also been used for the JDBC interfaces (Statement and all Subinterfaces, ResultSet, etc).

    I think you end up having to close those objects just as often as IO (depending on what you are doing, of course)

    Rob
    http://www.robsite.org
  29. Five favorite features in Java 5[ Go to top ]

    Have to say, mine are the one that did not make it in. Like pointers and direct memory manipulation.

    Other than that they managed to give us a lot of the stuff I came to detest in C++ plus a number of yet more unnecessary syntax sugar, including but not limited to the increased disability of reading code as it is (read: annotations) - itself in an awkward syntax btw., variable arguments lists, the inclusion of whole new language construct with the sole purpose of using it in a single library (read: Generics for Collections). Let alone cowardice (failure scrapping the primitives!)

    I do like the foreach loop though it is totally superficial :-).