Download
java 5 new language features n.
Skip this Video
Loading SlideShow in 5 Seconds..
Java 5: New Language Features PowerPoint Presentation
Download Presentation
Java 5: New Language Features

Java 5: New Language Features

311 Vues Download Presentation
Télécharger la présentation

Java 5: New Language Features

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Java 5:New Language Features Eben Hewitt August 2005

  2. Goal of this Presentation • Understand new language constructs in JDK 5 • Understand additions/changes to the API • See the usefulness of new features in real examples • Tie concepts back to our organization • Does not include topics in coming presentations

  3. Coming JDK 5 Presentations • Generics • Annotations • Concurrency • Instrumentation

  4. Topics in this Presentation • JDK 5 Overview • Swing Things • For-Each Loop • Static Imports • Autoboxing • Typesafe Enums • Var-args //cont...

  5. Topics in this Presentation cont. • Covariants • Able-Interfaces • Formatter • Scanner • Xpath Improvements • Miscellaneous Features • StringBuilder • Hexadecimal FP Literals • Regex Improvements • Reasons to Migrate

  6. JDK 5 Overview • Implements 15 new JSRs • See JSR 176 • http://www.jcp.org/en/jsr/detail?id=176 • Performance Improvements

  7. Swing Things

  8. Adding Components In JDK 1.4 to add a component to the "content pane": JComponent component; JFrame frame; //create component and frame frame.getContentPane().add(component); In JDK 5, Swing does it for you: JComponent component; JFrame frame; //create the component and frame frame.add(component);

  9. Desktop Enhancements • Look and feel: Ocean, Synth • JTable printing • Multilingual fonts

  10. Ocean Look and Feel • Default LNF • It’s a private custom MetalTheme, so your custom MetalThemes won’t be affected.

  11. Ocean Screenshot

  12. Synth—The Skinnable LNF • Enables creating a custom look without code. • Allow appearance to be configured from images. • Provide the ability to customize the look of a component based on its name property. • Provide a centralized point for overriding the look of all components. • Enable custom rendering based on images.

  13. Synth Look and Feel cont. • No way to specify layout. • No default look! Synth is an empty canvas. Has NO default bindings and, unless customized, paints nothing. • Synth DTD: http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/synth/doc-files/synthFileFormat.html • javax.swing.plaf.synth

  14. Synth Implementation Screenshot

  15. Synth Example //Demo SynthExample.java

  16. Printable JTables • No-arg print() method prints the JTable with no header or footer • selects FIT_WIDTH print mode (as opposed to NORMAL). • Opens the print dialog (default).

  17. Printable Jtables cont... try { print(PrintMode.NORMAL, new MessageFormat( "Personal Info"), new MessageFormat("Page {0,number}")); } catch (PrinterException e) { e.printStackTrace(); } //Header will be bold faced and centered, and contain the text "Personal Info". //Footer will consist of the centered text "Page 1".

  18. For-Each Loop

  19. For-Each Loop means... • Don’t have to calculate loop beginning and end • Don’t have to get parameterized Iterator. • Works with Collections and Arrays

  20. For-Each Syntax for (Product p : Cart) Read this as: For each Product object in the Collection of Products called Cart, execute the body of the loop. Call the current Product in the iteration “p”. //Demo DemoForEach.java

  21. Iterable interface • For/Each loop is made possible by newjava.lang.Iterableinterface. • Must implement this interface if you want your class available for For/Each loop. public interface Iterable<T>{Iterator<T> iterator();}

  22. AbstractCollection AbstractList AbstractQueue AbstractSequentialList AbstractSet ArrayBlockingQueue ArrayList AttributeList BeanContextServicesSupport BeanContextSupport ConcurrentLinkedQueue CopyOnWriteArrayList CopyOnWriteArraySet DelayQueue EnumSet HashSet JobStateReasons LinkedBlockingQueue LinkedHashSet LinkedList PriorityBlockingQueue PriorityQueue RoleList RoleUnresolvedList Stack SynchronousQueue TreeSet Vector Implementing Iterable:

  23. For-Each and Casting • You must use Generics if you need to cast on retrieval. void cancelAll(Collection<TimerTask> c) { for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); ) i.next().cancel(); } Eliminate Iterator: void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) t.cancel();

  24. For-Each Loop Advantages • Simpler • Easier to read • Because you don’t need to declare the iterator, you don’t have to parameterize it.

  25. For-Each Restrictions You cannot use for-each to: • Remove elements as you traverse collections (hides the Iterator) • Modify the current slot in an array or list • Iterate over multiple collections or arrays in parallel

  26. For-Each Recommendations • Use the for-each loop anywhere and everywhere possible.

  27. Static Imports

  28. Static Imports allow you to... • Import static members one at a time: import static java.lang.Math.PI; • or everything in a class: import static java.lang.Math.*; • Note you must fully qualify imports. • The compiler will indicate ambiguities.

  29. Static Imports Recommendations • Use it when you: • Require frequent access to static members from one or two classes • Overuse can make your program unreadable and unmaintainable. • Import members individually by name, not using *. • Organize static imports above regular imports in class definition

  30. Autoboxing

  31. Autoboxing • Automatically converts a primitive type to its corresponding wrapper when an object is required. • Automatically converts a wrapper to its corresponding primitive when a primitive is required. • Once values are unboxed, standard conversions apply

  32. Autoboxing Occurs… • In method and constructor calls • In expressions • In switch/case statements

  33. Autoboxing Example ArrayList<Integer> ints = new ArrayList<Integer>(1); ints.add(1); for (int i : ints) { ints.get(0); } //remember--you can’t modify the list in the for loop!

  34. Quiz • Is this valid? Boolean b = FALSE; while(b) { }

  35. Beware Comparisons //prints TRUE in Java 5 //but is ILLEGAL in Java 1.4 System.out.println(new Integer(7) == 7);

  36. Quiz • What values for i and j make this an infinite loop? while (i <= j && j <= i && i != j){ }

  37. Autobox Recommendations • Nice shortcut when meaning is clear. • Use primitives wherever you don’t require an object. • Be very careful when using in comparisons. • Be careful when using in conjunction with varargs feature.

  38. Typesafe Enums

  39. Enum Overview • C/C++ has had first-class enums for years. • Java developers had to do this: static final int SMALL = 0; static final int MEDIUM = 1; static final int LARGE = 2; What’s the problem with this?

  40. Answer • Nothing prevents this: int shirtSize = 42;

  41. Enum Traits • Can be declared in a class but not in a method. • Can have constructors and methods. • Cannot directly instantiate an enum. • Values must be very first declaration. • AlsoEnumSet<E extends Enum<E>>and EnumMap<K extends Enum<K>,V>

  42. Simplest Enum Example public enum Size { SMALL, MEDIUM, LARGE, XLARGE } Size shirtSize = Size.LARGE; //DEMO: EnumDemo.java

  43. Complex Enums //Demo EnumDemo2.java

  44. EnumSet public abstract class EnumSet <E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable

  45. EnumSet • Set implementation for use with Enums • All elements must come from a single enum. • Internally represented as bit vectors for speed. • Not synchronized • The Iterator returned: • traverses elements in declared ordered • is weakly consistent.

  46. EnumSet Declaration public abstract class EnumSet <E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable

  47. EnumSetDemo //Demo EnumSetDemo.java

  48. DTE Enum Example • We could use enums in DateTimeUtils class to represent the different allowable formats: public static Date stringToDate(String input, int format) switch (format) { case YYYY_MM_DD_DATE_FORMAT: case MM_SLASH_DD_SLASH_YYYY_DATE_FORMAT: //etc.

  49. Enum Example from the API: • java.util.conncurrent.TimeUnit:MICROSECONDS, MILLISECONDS, NANOSECONDS, SECONDS • Example: TimeUnit.MILLISECONDS.sleep(200);

  50. Enum Advantages • Compile-time and runtime checks • Can do almost everything a class can do • Don’t get confused by which ints to pass in in a big hierarchy like Swing’s