1.16k likes | 1.56k Views
Java 5: New Language Features Eben Hewitt August 2005 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
E N D
Java 5:New Language Features Eben Hewitt August 2005
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
Coming JDK 5 Presentations • Generics • Annotations • Concurrency • Instrumentation
Topics in this Presentation • JDK 5 Overview • Swing Things • For-Each Loop • Static Imports • Autoboxing • Typesafe Enums • Var-args //cont...
Topics in this Presentation cont. • Covariants • Able-Interfaces • Formatter • Scanner • Xpath Improvements • Miscellaneous Features • StringBuilder • Hexadecimal FP Literals • Regex Improvements • Reasons to Migrate
JDK 5 Overview • Implements 15 new JSRs • See JSR 176 • http://www.jcp.org/en/jsr/detail?id=176 • Performance Improvements
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);
Desktop Enhancements • Look and feel: Ocean, Synth • JTable printing • Multilingual fonts
Ocean Look and Feel • Default LNF • It’s a private custom MetalTheme, so your custom MetalThemes won’t be affected.
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.
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
Synth Example //Demo SynthExample.java
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).
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".
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
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
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();}
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:
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();
For-Each Loop Advantages • Simpler • Easier to read • Because you don’t need to declare the iterator, you don’t have to parameterize it.
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
For-Each Recommendations • Use the for-each loop anywhere and everywhere possible.
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.
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
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
Autoboxing Occurs… • In method and constructor calls • In expressions • In switch/case statements
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!
Quiz • Is this valid? Boolean b = FALSE; while(b) { }
Beware Comparisons //prints TRUE in Java 5 //but is ILLEGAL in Java 1.4 System.out.println(new Integer(7) == 7);
Quiz • What values for i and j make this an infinite loop? while (i <= j && j <= i && i != j){ }
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.
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?
Answer • Nothing prevents this: int shirtSize = 42;
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>
Simplest Enum Example public enum Size { SMALL, MEDIUM, LARGE, XLARGE } Size shirtSize = Size.LARGE; //DEMO: EnumDemo.java
Complex Enums //Demo EnumDemo2.java
EnumSet public abstract class EnumSet <E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable
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.
EnumSet Declaration public abstract class EnumSet <E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable
EnumSetDemo //Demo EnumSetDemo.java
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.
Enum Example from the API: • java.util.conncurrent.TimeUnit:MICROSECONDS, MILLISECONDS, NANOSECONDS, SECONDS • Example: TimeUnit.MILLISECONDS.sleep(200);
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