java generics
TRANSCRIPT
- 1. J2SE 5.0 Generics
- Carol McDonald
-
- Java Technology Architect
-
-
- Sun Microsystems, Inc.
-
2. Speakers Qualifications
- CarolcDonald:
-
- Java Architect at Sun Microsystems
-
- Before Sun, worked on software development of:
-
-
- Application tomanage car LoansforToyota(>10 million loans)
-
-
-
- PharmaceuticalIntranet( RocheSwitzerland)
-
-
-
- TelecomNetwork Mgmt( DigitalFrance)
-
-
-
- X.400Email Server( IBMGermany)
-
3. Java SE 1.5 Language Changes 4. Seven Major New Features
- Generics
- Autoboxing/Unboxing
- Enhanced for loop (foreach)
- Type-safe enumerations
- Varargs
- Static import
- Metadata
5. Generics 6. Is there a problem in here? Vector v = new Vector(); v.add(newInteger (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) if ((( String )it.next()).length() == 4) it.remove(); } 7. The Problem (Pre-J2SE 5.0) Vector v = new Vector(); v.add(newInteger (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(); } 8. Generics
- Problem: Collection element types
-
- Compiler is unable toverify types
-
- Assignment must use thecastoperator
-
- This can generate runtime errors ( ClassCastException )
- Solution:
-
- Tell the compiler what typethe collection is
-
- Let the compiler fill in thecast
9. Using Generic Classes
- Instantiate agenericclass to create type specific object
- Example
- Vector x = new Vector ();
- x.add(new Integer(5)); // Compiler error!
- Vector y = new Vector ();
10. Wildcards
- Method to print contents of any Collection?
- Wrong!
- Passing aCollection of type Stringwill give acompiler error
void printCollection(Collection c) { for (Object o : c)System.out.println( o ); } 11. Wildcards
- Correct way:
- ?is thewildcardtype
- Collection means Collection ofunknown
void printCollection( Collectionc) { for (Object o : c)System.out.println(o); } 12. Bounded Wildcards
- A wildcard can be specified with anupper bound
public voiddrawAll (List< ? extends Shape >s) { ... } List c = getCircles(); drawAll(c) ; List t = getTriangles(); drawAll(t) ; 13. Autoboxing & Unboxing 14. Autoboxing/Unboxing of Primitive Types
- Problem: (pre-J2SE 5.0)Conversion betweenprimitivetypes andwrappertypes (and vice-versa)
-
- must manually convert a primitive type to a wrapper type before adding it to a collection
-
- inti= 22;
-
- List l = new LinkedList();
-
- l.add( new Integer(i) );
15. 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();
-
- al .add( i );//Autoboxing conversion
16. Enhanced for Loop 17. 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
18. Enhanced for Loop Example
- Oldcode pre-J2SE 5.0
-
- void cancelAll(Collection c) {
-
- for ( Iterator i = c.iterator(); i.hasNext() ; ){
-
-
- TimerTask task =(TimerTask) i.next();
-
-
-
- task.cancel();
-
-
-
- }
-
-
- }
- NewCode
-
- void cancelAll(Collection 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
19. Type-safe Enumerations 20. 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
-
- enumtype has public, self-typed members for each enum constant
-
- enum Season { WINTER, SPRING, SUMMER, FALL }
21. Enumeration Example: public classCard{ publicenum Suit{ spade, diamond, club, heart }; publicenum Rank{ace, two, three, four, five,six, seven, eight, nine, ten,jack, queen, king }; privateCard (Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } } List< Card >deck= new ArrayList< Card >(); for ( Suitsuit :Suit.values ()) for ( Rankrank :Rank.values ()) deck.add(new Card(rank, suit)); Think how much JDK1.4 code this would require! 22. Varargs 23. Before Varargs Example//example method that takes a variable number ofparameters 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 avariable number of parameters
-
- Can be done with an array, but caller has to create the array first
24. 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(...)
25. Varargs examples
- APIs have been modifiedso that methods accept variable-length argument listswhere 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);
26. Static Imports 27. Static Imports
- Problem: (pre-J2SE 5.0)
-
- Having to fully qualify every static referenced from external classes
- Solution: New import syntax
-
- importstaticTypeName.Identifier;
-
- importstaticTypename.*;
-
- Also works for static methods and enums
-
- e.gMath.sin(x)becomessin(x)
28. Formatted I/O 29. Simple Formatted I/O
- Printfis 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);
30. Annotations 31. Annotations Metadata (JSR-175)
- Provide standardised way ofadding annotationsto Java code
-
- public@Remotevoid foo() {}
- Annotations areused by toolsthat work with Java code:
-
- Compiler
-
- IDE
-
- Runtime tools
- Used togenerateinterfaces, deployment descriptors...
32. Annotations Example: JAX-RPC
- Old Code
- public interfacePingIFimplements java.rmi.Remote{
-
- public void foo()throws java.rmi.RemoteException;
-
- }
-
- public class Pingimplements PingIF{
-
- public void foo() {...}
-
- }
- New Code
-
- public class Ping {
-
- public@Remotevoid foo() {}
-
- }
33. Resources and Summary 34. 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
35. 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
-
36. Resources
- http://java.sun.com/javase
- Java.net
- http://jdk.dev.java.net
37. 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
38. Thank You!
- Carol McDonald
-
- Java Technology Architect
-
-
- Sun Microsystems, Inc.
-