J2SE 5.0 Generics    Carol McDonald Java Technology Architect Sun Microsystems, Inc.
Speaker’s Qualifications Carol  cDonald:  Java Architect at Sun Microsystems Before Sun, worked on software development of:  Application to  manage car Loans  for  Toyota  (>10 million loans)  Pharmaceutical  Intranet  ( Roche  Switzerland)  Telecom  Network Mgmt  ( Digital  France)  X.400  Email Server  ( IBM  Germany)
Java SE 1.5 Language Changes
Seven Major New Features Generics Autoboxing/Unboxing Enhanced for loop (“foreach”) Type-safe enumerations Varargs Static import Metadata
Generics
Is there a problem in here? Vector v = new Vector(); v.add(new  Integer (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) if ((( String )it.next()).length() == 4) it.remove(); }
The Problem (Pre-J2SE 5.0) Vector v = new Vector(); v.add(new  Integer (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) /*  ClassCastException   */ if ((( String )it.next()).length() == 4) it.remove(); }
Generics Problem: Collection element types Compiler is unable to  verify types Assignment must use the  cast  operator This can generate runtime errors ( ClassCastException ) Solution: Tell the compiler what type  the collection is Let the compiler fill in the  cast
Using Generic Classes Instantiate a  generic  class to create type specific object Example Vector <String>  x = new Vector <String> (); x.add(new Integer(5)); // Compiler error! Vector <Integer>  y = new Vector <Integer> ();
Wildcards Method to print contents of any Collection? Wrong! Passing a  Collection of type String  will give a  compiler error void printCollection(Collection <Object>  c) { for (Object o : c)  System.out.println( o ); }
Wildcards Correct way: ?  is the  wildcard  type Collection <?>  means Collection of  unknown void printCollection( Collection  <?>  c) { for (Object o : c)  System.out.println(o); }
Bounded Wildcards A wildcard can be specified with an  upper bound   public void  drawAll (List< ? extends Shape >s) { ... } List<Circle> c = getCircles(); drawAll(c) ; List<Triangle> t = getTriangles(); drawAll(t) ;
Autoboxing & Unboxing
Autoboxing/Unboxing of Primitive Types Problem: (pre-J2SE 5.0)  Conversion between  primitive  types and  wrapper  types (and vice-versa) must manually convert a primitive type to a wrapper type before adding it to a collection int  i  = 22; List l = new LinkedList(); l.add( new Integer(i) );
Autoboxing/Unboxing of Primitive Types Solution: Let the compiler do it Integer   intObj  =  22 ;  // Autoboxing conversion int   i  =  intObj;   // Unboxing conversion ArrayList< Integer >  al  = new ArrayList<Integer>(); al .add( i );  //  Autoboxing conversion
Enhanced for Loop
Enhanced for Loop (foreach) Problem: (pre-J2SE 5.0) Iterating over collections is tricky Often, iterator only used to get an element Iterator is error prone  (Can occur three times in a for loop) Solution: Let the compiler do it New for loop syntax for (variable : collection) Works for Collections and arrays
Enhanced for Loop Example Old  code pre-J2SE 5.0 void cancelAll(Collection c) { for ( Iterator i = c.iterator(); i.hasNext() ; ){ TimerTask task =  (TimerTask) i.next(); task.cancel();  } } New  Code void cancelAll(Collection <TimerTask>  c) { for ( TimerTask task : c ) task.cancel(); } Iterating over collections,  tricky, error prone New for loop syntax: Let the compiler do it Works for Collections and arrays
Type-safe Enumerations
Type-safe Enumerations Problem: (pre-J2SE 5.0)  to define an enumeration: Defined a bunch of integer constants: public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; Issues of using Integer constants Not type safe (any integer will pass),Brittleness (how do add value in-between?), Printed values uninformative (prints just int values) Solution: New type of class declaration enum  type has public, self-typed members for each enum constant enum Season { WINTER, SPRING, SUMMER, FALL }
Enumeration Example: public class  Card  { public  enum   Suit  { spade, diamond, club, heart }; public  enum   Rank  {  ace, two, three, four, five,  six, seven, eight, nine, ten,  jack, queen, king }; private  Card (Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } } List< Card >  deck  = new ArrayList< Card >(); for ( Suit  suit :  Suit.values ()) for ( Rank  rank :  Rank.values ()) deck.add(new Card(rank, suit)); Think how much JDK1.4 code this would require!
Varargs
Before Varargs Example  //example method that takes a variable number of  parameters int sum( Integer[] numbers ) {  for(int i: numbers) // do something } // Code fragment that calls the sum method sum( new Integer[] {12,13,20} ); http://www.javaworld.com/javaworld/jw-04-2004/jw-0426-tiger1.html Problem: (in pre-J2SE 5.0)  To have a method that takes a  variable number of parameters Can be done with an array, but caller has to create the array first
Varargs Example  (Cont) //example method that takes a variable number of parameters int sum ( Integer... numbers )  { for(int i: numbers) // do something }  // Code fragment that calls the sum method sum( 12,13,20 ); http://www.javaworld.com/javaworld/jw-04-2004/jw-0426-tiger1.html Solution: Let the compiler do it for you: String format (String fmt,  Object... args);  Java now supports printf(...)
Varargs examples APIs have been modified  so that methods accept variable-length argument lists  where appropriate Class.getMethod Method.invoke Constructor.newInstance Proxy.getProxyClass MessageFormat.format New APIs do this too System.out. printf (“%d + %d = %d
”, a, b, a+b);
Static Imports
Static Imports Problem: (pre-J2SE 5.0) Having to fully qualify every static referenced from external classes Solution: New import syntax import  static  TypeName.Identifier; import  static  Typename.*; Also works for static methods and enums e.g  Math.sin(x)  becomes  sin(x)
Formatted I/O
Simple Formatted I/O  Printf  is popular with C/C++ developers Powerful, easy to use Finally adding printf to J2SE 5.0 (using varargs) out.printf(“%-12s is %2d long”, name, l); out.printf(“value = %2.2F”, value);
Annotations
Annotations Metadata (JSR-175) Provide standardised way of  adding annotations  to Java code public  @Remote  void foo() {} Annotations are  used by tools  that work with Java code: Compiler IDE Runtime tools Used to  generate  interfaces, deployment descriptors...
Annotations Example: JAX-RPC Old Code public   interface  PingIF  implements java.rmi.Remote  { public void foo()  throws java.rmi.RemoteException; } public class Ping  implements PingIF  { public void foo() {...} } New Code public class Ping { public  @Remote  void foo() {} }
Resources and Summary
For More Information (1/2) Memory management white paper http://java.sun.com/j2se/reference/whitepapers/ Destructors, Finalizers, and Synchronization http://portal.acm.org/citation.cfm?id=604153  Finalization, Threads, and the Java Technology Memory Model http://developers.sun.com/learning/javaoneonline/2005/coreplatform/TS-3281.html Memory-retention due to finalization article http://www.devx.com/Java/Article/30192
For More Information (2/2) FindBugs http://findbugs.sourceforge.net Heap analysis tools Monitoring and Management in 6.0 http://java.sun.com/developer/technicalArticles/J2SE/monitoring/ Troubleshooting guide http://java.sun.com/javase/6/webnotes/trouble/ JConsole http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html
Resources http://java.sun.com/javase Java.net http://jdk.dev.java.net
Stay in Touch with Java SE  http://java.sun.com/javase JDK Software Community planetjdk.org community.java.net/jdk JDK 6 http://jdk6.dev.java.net/ http://jcp.org/en/jsr/detail?id=270 JDK 7 http://jdk7.dev.java.net/ http://jcp.org/en/jsr/detail?id=277
Thank You! Carol McDonald Java Technology Architect Sun Microsystems, Inc.