Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2003 Langr Software Solutions. All rights reserved. Unleashing the Tiger Generics and Fun Stuff in J2SE 1.5 Jeff Langr Langr Software Solutions.

Similar presentations


Presentation on theme: "Copyright © 2003 Langr Software Solutions. All rights reserved. Unleashing the Tiger Generics and Fun Stuff in J2SE 1.5 Jeff Langr Langr Software Solutions."— Presentation transcript:

1 Copyright © 2003 Langr Software Solutions. All rights reserved. Unleashing the Tiger Generics and Fun Stuff in J2SE 1.5 Jeff Langr Langr Software Solutions http://www.LangrSoft.com December 2003

2 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger Tiger, Tiger Burning Bright Like a geek who works all night What new-fangled bit or byte Could ease the hacker's weary plight? -Joshua Bloch

3 Copyright © 2003 Langr Software Solutions. All rights reserved. What? Java community process (JCP) JSR's (Java Specification Requests) 14, 201, 175 Six areas of improvement Generics Enhanced for loop (foreach) Autoboxing; varargs Typesafe enums Static import Metadata Syntactic sugar

4 Copyright © 2003 Langr Software Solutions. All rights reserved. Other Interesting Items StringBuilderunsynchronized StringBuffer Both extend AbstractStringBuilder Two new look & feels: XP, Linux GTK 2.0 New API java.util.concurrent Updated XML support javac -Xlint warnings all, deprecation, unchecked, switchcheck, path, serial, finally Prefix with – to turn off System.nanoTime() No ties to system clock

5 Copyright © 2003 Langr Software Solutions. All rights reserved. Why? Make programs: Clearer Safer Shorter Easier to develop... without sacrificing compatibility Language supp't for common idioms Avoid boilerplate code Compete with C#

6 Copyright © 2003 Langr Software Solutions. All rights reserved. What not? Operator overloading Delegates Call by reference out / ref in C# const Default values on parms

7 Copyright © 2003 Langr Software Solutions. All rights reserved. How? Minimal byte code/VM changes Most changes to compiler and class library Collection classes retrofitted Still support legacy use Only new keyword is enum New keywords avoided Preserves compatibility Doesn't break code using keyword as identifier

8 Copyright © 2003 Langr Software Solutions. All rights reserved. How do I? Early access support from java.sun.com Adding Generics to the Java Programming Language Current version 2.2; July 23 Comes with a batch file = easiest Ant support Little IDE support yet CodeGuide – cost NetBeans can be configured to use it IDEA: generics support; free early access version jEdit (plugin) DrJava (drjava.org)

9 Copyright © 2003 Langr Software Solutions. All rights reserved. When? Next pre-release drop Real Soon Now Full customer ship initially slated for EOY 2003 Now probably August 2004 Betas in 1Q, 2Q 2004

10 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger To the most despised cast We'll bid a fond farewell at last With generics' burning spear The need for cast will disappear -Joshua Bloch

11 Copyright © 2003 Langr Software Solutions. All rights reserved. Using Generics aka parameterized types Provide type-safe collections Eliminates casting Collection example: List names = new ArrayList (); names.add("abc"); names.add("def"); String firstName = names.get(0); // names.add(new Date()); // compile error: cannot find symbol

12 Copyright © 2003 Langr Software Solutions. All rights reserved. Using Generics: Map Map example: Date today = new Date(); Date tomorrow = new Date(today.getTime() + 86400 * 1000); Map events = new HashMap (); events.put("today", today); events.put("tomorrow", tomorrow); today = events.get("today"); tomorrow = events.get("tomorrow");

13 Copyright © 2003 Langr Software Solutions. All rights reserved. Using Generics... Comparable example: class Employee implements Comparable { String id; Employee(String id) { this.id = id; } public int compareTo(Employee that) { return this.id.compareTo(that.id); }

14 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger While Iterators have their uses They sometimes strangle us like nooses With enhanced-for's deadly ray Iterator's kept at bay -Joshua Bloch

15 Copyright © 2003 Langr Software Solutions. All rights reserved. for-each Replaces standard iteration idiom: Iterator it = names.iterator(); while (it.hasNext()) { String string = (String)it.next(); System.out.println(string.toUpperCase()); }...with: for (String string: names) System.out.println(string.toUpperCase()); names must be bound to String i.e. List names

16 Copyright © 2003 Langr Software Solutions. All rights reserved. for-each Also works with arrays String[] names = { "a", "b", "c" }; for (String name: names) System.out.println(name.toUpperCase());

17 Copyright © 2003 Langr Software Solutions. All rights reserved. Making Your Class Iterable java.lang now contains the Iterable interface class Department implements Iterable { private List employees = new ArrayList (); public Iterator iterator() { return employees.iterator(); } public void hire(Employee employee) { employees.add(employee); } You can now use for-each (next page)

18 Copyright © 2003 Langr Software Solutions. All rights reserved. Using an Iterable Class Can use for-each to iterate all emps in dept: Department dept = new Department(); dept.hire(new Employee("1")); dept.hire(new Employee("2")); for (Employee emp: dept) System.out.println(emp); Doesn't work in public pre-release compiler...Yet. Works in limited availability beta. You must cast the collection being iterated: for (Employee emp: (Iterable )dept)

19 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger When from collections ints are drawn Wrapper classes make us mourn When Tiger comes, we'll shed no tears We'll autobox them in the ears -Joshua Bloch

20 Copyright © 2003 Langr Software Solutions. All rights reserved. Autoboxing Currently: List grades = new ArrayList(); grades.add(new Integer(10)); int grade = ((Integer)grades.get(0)).intValue(); System.out.println("" + grade); With autoboxing: List grades = new ArrayList (); grades.add(10); int grade = grades.get(0); System.out.println(grade);

21 Copyright © 2003 Langr Software Solutions. All rights reserved. Autoboxing Notes Autounboxing not working in 2.2 drop Must do: int grade = grades.get(0).intValue(); Autoboxing only on parms. Can't do: 10.toString(); // not yet? Ever? Autoboxing creates new wrapper objects Expensive for large volume Autounboxing null from a map Throws NullPointerException, on assignment only Collections.getWithDefault() ? (not yet)

22 Copyright © 2003 Langr Software Solutions. All rights reserved. Varargs Variable-length argument lists Department dept = new Department(); dept.hire( new Employee("1"), new Employee("2"), new Employee("3")); dept.hire(new Employee("4")); // code in Department: public void hire(Employee... hires) { for (Employee employee: hires) employees.add(employee); }

23 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger The int-enum will soon be gone like a foe we've known too long With typesafe-enum's mighty power Our foe will bother us no more -Joshua Bloch

24 Copyright © 2003 Langr Software Solutions. All rights reserved. Typesafe enum Uses Bloch's Typesafe Enum pattern An enum declares a new, serializable type, with named instances: enum Grade { A, B, C, D, F }; The Student class: class Student { List grades = new ArrayList (); void add(Grade g) { grades.add(g); } Grade getGrade(int i) { return grades.get(i); }

25 Copyright © 2003 Langr Software Solutions. All rights reserved. Using enum Referred to like a static variable Student student = new Student(); student.add(Grade.A); May be used in switch statements switch (student.getGrade(0)) { case Grade.A: print("great"); break; case Grade.B: print("good"); break; case Grade.C: print("ok"); break; case Grade.D: print("eh"); break; case Grade.F: print("loser"); break; } Can't extend enums (keeps them safe)

26 Copyright © 2003 Langr Software Solutions. All rights reserved. Enhancing enum May have fields, constructors, methods enum Grade { A(4), B(3), C(2), D(1), F(0); private int points; public Grade(int p) { points = p; } public int points() { return points; } } class Student { //... double getGPA() { double total = 0.0d; for (Grade grade: grades) total += grade.points(); return total / grades.size(); }

27 Copyright © 2003 Langr Software Solutions. All rights reserved. Polymorphic enums Enum constants allow method declarations abstract enum StudentType { REGULAR { double getGPA(List grades) { double total = 0.0d; for (Grade grade: grades) total += grade.getGradePoints(); return total / grades.size(); } }, SENATORS_SON { double getGPA(List grades) { return 4.0d; } }; abstract double getGPA(List grades); }

28 Copyright © 2003 Langr Software Solutions. All rights reserved. Additional enum Fields Get the collection of enum values for (Grade grade: Grade.VALUES) System.out.println(grade); Construct by name Grade grade = Grade.valueOf("F"); Obtain ordinal, name enum Grade { //... public String toString() { return "(" + ordinal + ") " + name + "; points = " + points; }

29 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger And from the constant interface we shall inherit no disgrace With static import at our side, our joy will be unqualified -Joshua Bloch

30 Copyright © 2003 Langr Software Solutions. All rights reserved. Static Import Eliminate bad Constant Interface pattern Interfaces should be used to define types Poor design; exposes impl details to clients Locks class to always import constant interface Imports all static methods of a class Currently: public double hypotenuse(double a, double b) { return Math.sqrt( Math.pow(a, 2.0) + Math.pow(b, 2.0)); }

31 Copyright © 2003 Langr Software Solutions. All rights reserved. Static Import Now: import static java.lang.Math.*; class Test { public double hypotenuse(double a, double b){ return sqrt(pow(a, 2.0) + pow(b, 2.0)); } Single fields/static methods can also be imported: import static java.lang.Math.PI;

32 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger And as for noble metadata I'll have to sing its praises later Its uses are so numerous To give their due, I'd miss the bus -Joshua Bloch

33 Copyright © 2003 Langr Software Solutions. All rights reserved. Metadata (Speculative) JSR 175 Annotated code to help support tools Similar to C# attributes Example use in C#: NUnit Will probably use @ annotation-type-> a-t -> @ ;-) Example: mark a method so web services tool can autogen IF public class CoffeeOrder { @Remote public Coffee [] getPriceList() {... }} Will allow you to create your own @ tags

34 Copyright © 2003 Langr Software Solutions. All rights reserved. Generics Revisited Test: public void testFirst() { NumList nums = new NumList (); nums.add(5); nums.add(25); nums.add(125); assertEquals(5, nums.getFirst()); } NumList is a parameterized type

35 Copyright © 2003 Langr Software Solutions. All rights reserved. Type Parameters is a type parameter list T is a naked type parameter import java.util.*; class NumList { private List numbers = new ArrayList (); public void add(T number) { numbers.add(number); } public T getFirst() { return numbers.get(0); }

36 Copyright © 2003 Langr Software Solutions. All rights reserved. Constrained Generics Allow only numerics: use a bound class NumList { Allows this (in NumList): public double total() { double total = 0.0d; for (T number: numbers) total += number.doubleValue(); return total; } Disallows this (in client): NumList dateNums = new NumList (); Default bound is java.lang.Object

37 Copyright © 2003 Langr Software Solutions. All rights reserved. Wildcards Allows substituting any type Can have bounds public void addAll(NumList src) { for (T number: src.numbers) numbers.add(number); }

38 Copyright © 2003 Langr Software Solutions. All rights reserved. Generic Methods, Super Parameter section precedes return type static void add(T element, NumList list) { list.add(element); } element can be added to a NumList bound to a supertype of T

39 Copyright © 2003 Langr Software Solutions. All rights reserved. Additional Bounds (&) Specify additional interface bounds w/ & Can be used to enforce parameter types T min(T first, T second) { return avg(first) < avg(second) ? first : second; } double avg(T list) { return list.total() / list.size(); } Perhaps useful when you can't change the parameterized type

40 Copyright © 2003 Langr Software Solutions. All rights reserved. Implementation: Erasure List is erased to List Naked type parm T erased to its upper bounds Object by default Run javac -s to see generated code Send output (.java) to a different directory The pre-release doesn't protect you from overwriting source!

41 Copyright © 2003 Langr Software Solutions. All rights reserved. Limitations Can't use primitives for type parms But there's autoboxing Can't use naked type parms in: statics, casts, instanceof, new, implements/extends Can't use type variables in catch clauses Arrays of generic types not allowed Except List []

42 Copyright © 2003 Langr Software Solutions. All rights reserved. Raw Types Legacy use of parameterized types is OK NumList g = new NumList(); g.add("s"); // will not compile Resolves to upper bounds Generates unchecked warnings. For details: -warnunchecked (pre); -Xlint:unchecked (beta) Use casts to (evilly) circumvent type checks List e = new ArrayList (); ((List)e).add(3); Evil begets evil: String e0 = e.get(0);...generates a ClassCastException

43 Copyright © 2003 Langr Software Solutions. All rights reserved. More Topics (briefly)... Overloading rules Class can't have two methods w/ same name and erasure Bridge methods Covariant return types Reflections

44 Copyright © 2003 Langr Software Solutions. All rights reserved. Bridge Methods Maybe necessary in override situations: class Emp { abstract T id(T x); } class USEmp extends Emp { String id(String x) { return x; } } Generates: class Emp { abstract Object id(Object x); } class USEmp extends Emp { String id(String x) { return x; } Object id(Object x) { return id((String)x); } }

45 Copyright © 2003 Langr Software Solutions. All rights reserved. Multiple Return Types! class Bucket { abstract T next(); } class LeakyBucket extends Bucket { String next() { return ""; } } Generates: class Bucket { abstract Object next(); } class USEmp extends Emp { String next() { return ""; } /*synthetic*/Object next() { return this.next(); } } Would be compile error if original source Bytecodes generated are ok Since methods use full sig at bytecode level

46 Copyright © 2003 Langr Software Solutions. All rights reserved. Covariant Return Types Return type varies in same direction as containing type class Bag { Bag copy() { return this; } } class LeakyBag extends Bag { LeakyBag copy() { return this; } } Generates: class Bag { Bag copy() { return this; } } class LeakyBag extends Bag { LeakyBag copy() { return this; } /*synthetic*/ Bag copy() { return this.copy(); } }

47 Copyright © 2003 Langr Software Solutions. All rights reserved. Reflections class Class { T newInstance(); public Constructor getConstructor(Class... parmTypes); public Constructor getDeclaredConstructor(Class... parameterTypes); class Constructor { public T newInstance() public Class getDeclaringClass(); public T newInstance(Object... initargs); X.class has type Class For expression e of static type X e.getClass() is of type Class Example use: declaring truly typesafe wrapper

48 Copyright © 2003 Langr Software Solutions. All rights reserved. Take Care... Previous limitations and rules suggest how complex generics can be If you're unsure... Good: Read the spec Better: Try itwrite a test! Best: Avoid it If you're having a tough time coding it... Others will have a tough time maintaining it

49 Copyright © 2003 Langr Software Solutions. All rights reserved. Tiger Oh Tiger of sugar, oh Tiger of fluff, Many nice features to call C#'s bluff, My only warning for this endeavor: Just make sure you aren't too clever! -Jeff Langr


Download ppt "Copyright © 2003 Langr Software Solutions. All rights reserved. Unleashing the Tiger Generics and Fun Stuff in J2SE 1.5 Jeff Langr Langr Software Solutions."

Similar presentations


Ads by Google