84
Java Programming Transparency No. 1 Lecture 13 Java 1.5 New language Features : Cheng-Chia Chen

Java Programming Transparency No. 1 Lecture 13 Java 1.5 New language Features : Cheng-Chia Chen

  • View
    240

  • Download
    0

Embed Size (px)

Citation preview

Java Programming

Transparency No. 1

Lecture 13

Java 1.5

New language Features :

Cheng-Chia Chen

Java Collection

Transparency No. 2

History of Java Language

1995 (1.0) – First public release. 1997 (1.1) – Nested classes added. 2001 (1.4) – Assertions added. 2004 (1.5) – Significant new Language

features added.

Java Collection

Transparency No. 3

Contents

1.4 new assert statement 1.5 new Java Language Features

Autoboxing Static Import Variable Arguments (“Varargs”) Enhanced for loop Generics Typesafe enums Annotation

Some useful new IO: Scanner() PrintStream.printf(), Formatter class

Java Collection

Transparency No. 4

Autoboxing / Unboxing Example

Traditional “boxing” example (prior to 1.5) :Vector idList = new Vector();

. . .

int idNum = getIdNumber();

. . .

Integer idInteger = new Integer(idNum);

idList.add(idInteger);

We have to convert from int to Integer since Vector requires its contents to be objects.

Java Collection

Transparency No. 5

Autoboxing / Unboxing Example

“Autoboxing” example: (now in 1.5)

Vector idList = new Vector();

. . .

int idNum = getIdNumber();

. . .

idList.add(idNum);

No need for an explicit conversion to Integer. The compiler(not JVM) will do that for us!!

Java Collection

Transparency No. 6

Autoboxing / Unboxing

boxing: Integer I = new Integer (2); manual boxing Integer I = 2; autoboxing

unboxing: Integer J = new Integer(10); int i = J.intValue(); manual unboxing int i = J auto unboxing

Autoboxing and Unboxing Automatic conversion by the compiler Automatically part of method invocation, assignment conversion,

numeric promotion. long x1 = new Integer(2); m1(Double); invoked by m1(2.0f)

Java Collection

Transparency No. 7

Autoboxing / Unboxing Example

Autoboxing/Unboxing used in other ways.

double area(double height, double width) { return height * width;

}... Double h = new Double(…); double w = …; double a = area(h,w); Double A = area(h,w);

What are wrong prior to 1.5 ? Now all are legal in 1.5!

Java Collection

Transparency No. 8

Autoboxing / Unboxing Example 3

Mixing primitives and objects:

Double price = new Double(123.45);

Double tax = price * 0.05;

double fee = 5.95;

Double totalPrice = price + tax + fee;

Java Collection

Transparency No. 9

importing Java classes

to use java.lang.Math.import java.lang.Math;

double radians = Math.toRadians(30.0);

double unity = Math.pow(Math.sin(radians),2.0) + Math.pow(Math.cos(radians),2.0);

double areaCircle = Math.PI * Math.pow(10.0,2.0);

Java Collection

Transparency No. 10

Importing Static Members

Before 1.5 Even importing a class or interface

Class name is needed to access static members.

Static Import A variant of the import statement. Import static methods and fields. Similar to the import of classes and interfaces from a

package. Import individual members, or collectively.

Java Collection

Transparency No. 11

With Static Import

No need to reference Math, except in import.import static java.lang.Math.*;

import static java.System.out;

double radians = toRadians(30.0);

double unity = pow(sin(radians),2.0) + pow(cos(radians),2.0);

double areaCircle = PI * pow(10.0,2.0);

out.println(“...“); //(o)

err.println(“...“); // (X) not imported

Java Collection

Transparency No. 12

pros and cons of Importing Static Members

Code is more readable. No need to reference the class or interface names.

Code can be less understandable. No reference to class or interfaces names.

Implementation detail exposed.Commitment to the implementation.

Java Collection

Transparency No. 13

Iterations (I)

Vector tasks = new Vector(); . . .Iterator iter = tasks.iterator();

while ( iter.hasNext() ) { work( (Task) iter.next() );}

A common Java “idiom” for iteration. Is this the best way to iterate through a collection?

Java Collection

Transparency No. 14

Iterations (II)

Vector tasks = new Vector();

. . .

for (Iterator iter = tasks.iterator(); iter.hasNext(); ) {

work( (Task)iter.next() );

}

Another common Java “idiom” for iteration. Is this any better?

Java Collection

Transparency No. 15

Iterations (III)

How about iterating through arrays?

Task[] tasks = { … };

. . .

for ( int i = 0; i < tasks.length; ++i ) {

work( tasks[i] );

}

Is looping through an array any better?

Java Collection

Transparency No. 16

Enhanced for loop

Iterations over collections are painful. Iterator is only used to get elements. Iterators can be error-prone.

Iterator variable used in for loop three times – two opportunities to get it wrong.

Common cut and paste errors.

A “foreach” style loop construct would be better.

It would be nice if the compiler iterates for you

Java Collection

Transparency No. 17

Enhanced for loop for Collections

For collections (or more accurately, Iterable object ):Vector tasks = new Vector(); . . .for ( Object task : tasks ) { work( (Task)task );}

Using the enhanced for loop is much clearer. But still need the cast to Task. will be corrected when using generic types.

Java Collection

Transparency No. 18

Enhanced for loop for Arrays

For arrays:

Task[] tasks = { … };

. . .

for ( Task t : tasks ) {

work(t);

}

Again, using the enhanced for loop is clearer. no cast to Task is needed.

Java Collection

Transparency No. 19

Enhanced for loop Restrictions

Restrictions Cannot be used to filter a collection.

i.e., remove elements Cannot modify the current slot in an array or list.

e.g., replace the entire element

When to use enhanced for-loop? use enhanced for-loop for simple iteration (e.g., no need t

o know the position of elements). Complicated processing left to traditional for or while

loops.

Java Collection

Transparency No. 20

How to pass a variable number of arguments to a method?

use an array.

double sum(double from, double[] dArg) {

double total = from;

for ( double d : dArg )

total += d;

return total;

}

But …

Java Collection

Transparency No. 21

variable argument method

… you have to compose the array!

double[] dblArray = { book, fruit, drink, 2 };

double total = sum(100.0, dblArray);

This is inconvenient for a few, but a variable number of arguments …

Java Collection

Transparency No. 22

Use “Varargs” for a variable number of arguments We want to call sum() method with as many arguments as nee

ded.

sum(1.1,2.2);sum(1,2.3,4.56,7.89,101);sum(5.0);

Also, use Auto unboxing to sum any kind of Numeber objects passed to sum().

sum(93, 7.6f, 8.9, new Integer(45), new Double(78.9), 1234567890L);

Java Collection

Transparency No. 23

Define a method with a variable number of arguments Use the “Varargs” capability:

double sum(double from, double … dArg) { double total = from; for ( double d : dArg ) // dArg is an array!! total += d; return total;}

This notation (…) allows a variable number of arguments. Arguments to the method treated like an array.

Java Collection

Transparency No. 24

Varargs method invocation

can also call sum() with an array.double from = 10;

double dblArray[] = { . . . };

sum(10, dblArray);

But, not with both!

sum(1.2,3.4,4.5, dblArray); // Illegal!!

Java Collection

Transparency No. 25

More examples

invoke String.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) using reflection: (prior to 1.5) Class[] types = new Class[]{ int.class, int.class, char[].class, int.class }; Method m = String.class.getMethod(“getChars”, types ); m.invoke(“abcd”, new Object[] { new Integer(0), new Integer(2), new char[100], new Integer(0) } );

using varargs: (java 1.5) Method m = String.class.getMethod(“getChars”, int.class, int.class, char[].cla

ss, int.class); m.invoke(“abcd”, 0, 2, new char [100], 0);

Java Collection

Transparency No. 26

C-style printf()method

C-style printf() Uses a variable number of arguments (“varargs”). not provided prior to 1.5 since no varargs. Formatting options for each argument.

Common formats for numeric, string, and date/time.Layout justification and alignment.Locale-specific output

Normally used with System PrintStream System.out System.err

Java Collection

Transparency No. 27

printf()method example

System.out method call to printf():

System.out.printf(“%d %.2f %.2e\n", 78, 1.23456, 1.23456);

will print:

78 1.23 1.23e+00

Java Collection

Transparency No. 28

printf()method - numeric examples

Format Value Output

“%.2f” 1.23456 1.23

“%.2e” 1.23456 1.23e+00

“%,15.2f” -234567.8 -234,567.80

“%(,15.2f” -34567. (34,567.00)

“%x” 252 fc

“%4d” 5 5

“%04d” 78 0078

Java Collection

Transparency No. 29

printf()method - alignment examples

Format Value(s) Output

“%10s” “ABC” ABC

“%-10s” “ABC” ABC

“%10d” 123 123

“%-10d” 123 123

“%-10s %-2s %05d-%04d”

“Hartford”, “CT”, 6115, 11

Hartford CT06115-0011

Java Collection

Transparency No. 30

printf()method - Date (04/30/2006) examples

Format Output

“%tD” 04/30/06

“%tF” 2006-04-30

“%1$tb %1$te %1$ty” Sun 30 05

“%1$tA %1$tB %1$te, %1$tY”

Sunday April 30, 2006

“%1$tF %1$tr” 2006-04-30 10:45:00 AM

Java Collection

Transparency No. 31

Formatter class

Same C-style printf()capability Variable number of arguments (“varargs”) Same formatting options as printf(). used for possibly non-console output.

Used with: String File

Code similar to output streams. Not everyone sends output to:

System.out and System.err

Java Collection

Transparency No. 32

Formatter class example

java.util.Formatter formatter = new Formatter();

formatter.format( "%-10s %-2s ",“ABCD","CT");

formatter.format( "%05d-%04d",6115,11);

String s = formatter.toString();

formatter.close();

s now contains:

ABCD CT 06115-0011

Java Collection

Transparency No. 33

Generics

When you get an element from a collection, you have to cast

Casting is a pain Casting is unsafe—casts may fail at runtime

/* Removes all words longer than 10 from c; elements must be strings */ static void filter(Vector v) { for (Iterator i = v.iterator(); i.hasNext(); ) if( ((String) i.next()) .length() > 10) i.remove(); }// Alternative form - prettier? static void filter(Vector v) { for (Iterator i = v.iterator(); i.hasNext(); ){ String s = (String) i.next(); if(s.length() >10) i.remove(); }}

Java Collection

Transparency No. 34

Wouldn’t it be nice if you could tell the compiler what type a collection holds? Compiler could put in the casts for you They’d be guaranteed* to succeed

static void filter(Vector<String> c) {

for (Iterator<String> i = c.iterator();

i.hasNext(); )

if (i.next().length() > 10)

i.remove(); }

‧ Clearer and Safer

‧ No cast, extra parentheses, temporary variables

‧ Provides compile-time type checking

Java Collection

Transparency No. 35

potential problems for collections

Vector tasks = new Vector();tasks.add(task1);//ok now!! but cause bug in the futuretasks.add(“String”); tasks.add(task3); . . .for (Object task: tasks ) work((Task)task); //runtime Exception

It would be nice if the compiler could check members of a Collection for us!

Java Collection

Transparency No. 36

A “Generic” Collection Example Use angle brackets to indicate the Generic type.

Vector<Task> tasks = new Vector<Task>();

tasks.add(task1);

tasks.add(“String”); // Compile error!!!tasks.add(task5); . . .for(Task task: tasks ) work( task );

Vector tasks only allows Task objects to be added. No cast for Task needed in enhanced for loop.

Java Collection

Transparency No. 37

What are Generics?

Like a method allowing formal value parameters, Generics allows Classes, Interfaces and Methods to have formal type parameters. Eg: Stack< T>, Vector<U>, Queue<S>, Pair<A,B>…

When referencing a generic type/method, we can then pass the actual types. Eg: Stack<Book> s, Vector<Task> v, new Queue<Student>( …),…

Results Increased readability. Increased type safety.

Java Collection

Transparency No. 38

Build your own Generic class 1 – Defining the class

public class Cache<T> {

private T value;

public Cache(T v) {

value = v;

}

public T get() {

return value;

}

}

Java Collection

Transparency No. 39

Build your own Generic class 1 – Using the class

Cache<String> stringCache = new Cache<String>("abc");

String s = stringCache.get();

Cache<Integer> integerCache = new Cache<Integer>(new Integer(1));

Integer i = integerCache.get();

...

Java Collection

Transparency No. 40

Build your own Generic class 2: Defining Generic Methods

Not only class definition but can also method have formal type parameters.

// collection of generic array algorithm

class ArrayAlg {

public static <T> T getMiddle(T[] a){

return a[a.length / 2]);

} ...}

Java Collection

Transparency No. 41

Build your own Generic class 2: Using generic methods

String[] names = { “Wu", “Chen", “Wang" };

String middle = ArrayAlg.<String>getMiddle(names); //ok! // cf: in C++ we use ArrayAlg.getMiddle<String>(name)

String middle2 = ArrayAlg.getMiddle(names);// ok! compiler can infer the type of <T> from names.

String middle3 = ArrayAlg.<Integer> getMiddle(names); // err! type inconsistency

Java Collection

Transparency No. 42

Bounds for type parameters

class ArrayAlg {

// generic min method ; given an array, return its minimum

public static <T> T min(T[] a){ // almost correct

if (a == null || a.length == 0) return null;

T smallest = a[0];

for (int i = 1; i < a.length; i++)

if ( smallest.compareTo( a[i] ) >0 ) smallest = a[i];

return smallest; } } compile-error

Requirement: type <T> must implement Comparable!

Java Collection

Transparency No. 43

Bounds for type parameters

class ArrayAlg {

// generic min method ; given a array, return its minimum

public static <T extends Comparable> T min(T[] a){

if (a == null || a.length == 0) return null;

T smallest = a[0];

for (int i = 1; i < a.length; i++)

if ( smallest.compareTo( a[i] ) >0 ) smallest = a[i];

return smallest; } } use requirement: actual type <T> must implement Comparable!

ArrayAlg.<Object> min( … ) // error !! ArrayAlg.<String> min(…) // ok!

Java Collection

Transparency No. 44

Build your own Generic class 3 – Restricting the generic definition

Restricting the generic to a class or subclass.

public class Cache<T extends Person> {

. . .

}

Restrict the generic to class Person or its subclasses.

Cache<Person> pc = new Cache<Person>();// ok

Cache<Student> sc = new Cache<Student>(); //ok!

// error ! Computer is not a subclass of Person!

Cache<Computer> cc = new Cache<Computer>() // error

Java Collection

Transparency No. 45

Build your own Generic class 3 – Restricting the generic definition

Restricting the generic to a class or subclass implementing one or more interfaces.

public class Cache<T extends Person & canPlay & canWork> {

. . .}

Restrict the generic to class Person or its subclasses and interfaces canPlay and canWork. Note: Person can also be an interface.

Java Collection

Transparency No. 46

Generic types and raw types

What is the difference among: Vector -- use or definition; RAW Type Vector<T>; -- type definition Vector<String> -- type use Vector<Integer> … -- type use

The distinctions exist only at compilation time. For JVM (i.e. at runtime ), there is only the raw type definition: V

ector. All generic types definitions are compiled into a raw type by erasing all

type parameters. Therefore, you cannot define two generic types with the same raw type

within the same package. e.g. public class Pair<T>{…} public class Pair<S,T>{…} // type pair already defined.

Java Collection

Transparency No. 47

Generic type and raw type: generic type 1

public class Pair <T> { public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; }

public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } private T first; private T second; } Possible use: Pair<Person>, Pair<Point>,…

Java Collection

Transparency No. 48

Generic type and raw type: generic type 2

public class Pair <T1,T2>{ public Pair() { first = null; second = null; } public Pair(T1 first, T2 second) { this.first = first; this.second =

second; }

public T1 getFirst() { return first; } public T2 getSecond() { return second; } public void setFirst(T1 newValue) { first = newValue; } public void setSecond(T2 newValue) { second = newValue; }

private T1 first; private T2 second; }Possible use: Pair<Teacher, Student>, Pair<Male, Female>,…

Java Collection

Transparency No. 49

Generic type and raw type: raw type

public class Pair <T1,T2>{ public Pair() { first = null; second = null; } public Pair(T1 Object first, T2 Object second) { this.first = first; this.second

= second; }

public T1 Object getFirst() { return first; } public T2 Object getSecond() { return second; }

public void setFirst(T1 Object newValue) { first = newValue; } public void setSecond(T2 Object newValue) { second = newValue; }

private T1 Object first; private T2 Object second; }

Java Collection

Transparency No. 50

What happen if T extends Comparable & Serializable?

public class Pair <T extends Comparable & Serializable> { public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T max() { return first.compareTo(second) ? first: second ; } public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } private T first; private T second; } strategy:

T replaced by “Comparable” and cast to Serializable when necessary.

Java Collection

Transparency No. 51

The resulting raw type

public class Pair implement Serializable { public Pair() { first = null; second = null; } public Pair(Comparable first, Comparable second) { this.first = first;

this.second = second; } public Comparable max() { return first.compareTo(second) ? first: second ; } public Comparable getFirst() { return first; } public Comparable getSecond() { return second; } public void setFirst(Comparable newValue) { first = newValue; } public void setSecond(Comparable newValue) { second =

newValue; } private Comparable first; private Comparable second; }

Java Collection

Transparency No. 52

Translating generic expressions

For generic method invocation: Pair <Employee> buddies = … ; Employee buddy = buddies.getFirst();

After erasing: Pair <Employee> buddies = … ; Employee buddy = buddies.getFirst(); // of type Object!! need narrowin

g casting !! the compiler inserts casts since the return type has been erased

Pair buddies = … ; Employee buddy = (Employee) buddies.getFirst(); // safe casting !!.

field access also needs casting: Employee first = buddies.first; Employee first = (Employee) buddies.

first; setFirst(anEmployee ); // need casting ? ?

Java Collection

Transparency No. 53

Translating Generic Methods

before erasure: public static <T extends Comparable> T min(T[] a)

After erasure: public static Comparable min(Comparable[] a)

More complexity: public class DateInterval extends Pair<Date> { public void setSecond(Date second) { if( second.compareTo(getFirst()) ) { super.setSecond(second) ; } … }

After erasure: two setSecond(.) : 1. setSecond(Date) 2. setSecond(Object) from Pair

Java Collection

Transparency No. 54

Example Why doesn’t this work as expected?

Vector tasks = new Vector<Task>(); //(1) ok!tasks.add(task1);tasks.add(“String”);//(2) Not a Compile error!!!

tasks.add(policy5); . . .for ( Task task: Tasks ) work( task ); // Runtime error!!!

Why is adding this String not a compile error, but only a runtime error? for compatibility reason, (1),(2) are allowed.

Java Collection

Transparency No. 55

“Raw” and “Generic” Collections

The distinctions between “Raw” and “Generic” Collections. Raw Collections allow any Object. Generic Collections allow only objects of the declared Generic

type or subtype. Asymmetry on assignment of one type to the other:

Vector v = new Vector<Task>() // ok!

Vector<String> s = new Vector();

// compile error!! why?

Java Collection

Transparency No. 56

But Vector identical to Vector<Object> ?

Ans: NO!!Vector<Task> tasks = new Vector<Task>();

Vector<Object> tasks2 = tasks; // Compile error!!!

Vector tasks3 = tasks; // ok! for compatibility

Hence Vector is not the same as Vector<Object> Vector is a raw type, Vector<Object> is a generic Type.

Why “compile error” ?.

To prevent later errors such as:

tasks2.add(“String);

Task t = tasks2.get(0); Note:task3 suffers from the same possible error

Java Collection

Transparency No. 57

Generic collection permits subtype elements

Assume Homework is a subclass of Task.

Vector<Task> tasks = new Vector<Task>();

tasks.add(new Homework());

Homework home = tasks.get(0);

// Compile error!!! cast needed!

tasks is a generic Collection for Task, not Homework. Need a cast to Homework.

Java Collection

Transparency No. 58

“Generic” Collection Example #5

Assume driving is also a subclass of Task. Vector<Task> tasks = new Vector<Task>();tasks.add( new Driving() ); Homework home = (Homework)tasks.get(0);// Not a Compile error.// But, a ClassCastException at runtime!// same problem as raw type vector

tasks is a generic Vector for Task,a Driving task is added, but a Homework task is extracted.

Java Collection

Transparency No. 59

“Generic” Collection Example #6 Assume Homeowners and Auto are subclasses of

Policy.

List<Auto> autoPolicies = new ArrayList<Auto>();autoPolicies.add(new Auto());

List<Homeowners> homeownersPolicies = new ArrayList<Homeowners>();

homeownersPolicies.add(new Homeowners());

List<Policy> policies = new ArrayList<Policy>();policies.addAll(autoPolicies);policies.addAll(homeownersPolicies);

policies is a generic Collection for Policy, containing Homeowners and Auto policies.

Java Collection

Transparency No. 60

“Generic” Collection Example 7

Assume Auto is a subclass of Policy.

List<Auto> autoPolicies = new ArrayList<Auto>();autoPolicies.add(new Auto());

List<Policy> policies = new ArrayList<Policy>();policies = autoPolicies;// Compile error!

policies is an “incompatible type” for autopolicies! A List of Policy is not compatible with

a List of Auto.

Java Collection

Transparency No. 61

“Generic” Collection Example 7 Fix Assume Auto is a subclass of Policy.

List<Auto> autoPolicies = new ArrayList<Auto>();autoPolicies.add(new Auto());

List<? extends Policy> policies = new ArrayList<Policy>();

policies = autoPolicies;

policies is now “compatible” with autopolicies! The “? extends Policy” is a wildcard specification.

Java Collection

Transparency No. 62

What Generics are Not

Generics won’t catch every type error. If used with raw collections.

Generics are not templates. Generic declarations are type-checked. Generics compiled once and for all. Generic source code not exposed to user. No bloat/duplication required.

Java Collection

Transparency No. 63

Advantages of Generics

Catch type errors at compile time. Makes code more readable. e.g.,

List<Policy> Map<SocSecNo,Policy> Map<ClaimNo,LinkedList<Policy>>

Easy migration between raw collections and generic collections. i.e., both collection types can be interfaced.

Compatible with current Java technology.

Java Collection

Transparency No. 64

Disadvantages of Generics

Doesn’t catch all type errors at compile time. Makes generic code definitions less readable.

Take a look at the JavaDoc for the Generic Collection classes.

As we’ve seen, can be very tricky to use. One of the most controversial new features of Java 1.5.

Is it worth it?

Java Collection

Transparency No. 65

Standard Approach to Constant Enumerations – Definition

int enums

public class PolicyOperation { public static final int QUOTE = 1; public static final int ISSUE = 2; public static final int RENEW = 4; public static final int CANCEL = 12; public static final int ENDORSE = 16; public static final int CHANGE = 64; public static final int REINSTATE = 192; . . .

Java Collection

Transparency No. 66

Standard Approach to Constant Enumerations – Use

Use of PolicyOperation enum value

public void handle( int policyOperation) {

...

}

Policy policy = ...;

policy.handle(ISSUE);

Java Collection

Transparency No. 67

Typesafe Enums Disadvantages

Disadvantages Not type safe.

Can pass arbitrary values to methods.– e.g., policy.handle(912);

Cannot be caught at compile time.Values must be checked at run time.

– If checked at all

Constants are compiled into clients. Printed values are uninformative.

e.g., System.out.println(RESINSTATE); prints: 192

Java Collection

Transparency No. 68

New Solution –Typesafe Enum Pattern

Described in “Effective Java Programming Language Guide” by Joshua Bloch.

Pattern Class exports constants. No public constructor.

Advantages Fixes disadvantages of int enum pattern.

Java Collection

Transparency No. 69

Typesafe Enum Pattern

public static final PolicyOperation QUOTE = new PolicyOperation(1);

public static final PolicyOperation ISSUE = new PolicyOperation(2);

private int operation = 0;

private PolicyOperation(int op) {

this.operation = op;

}

public int getOperation() {

return this.operation;

}

Java Collection

Transparency No. 70

Typesafe Enum Pattern

Typesafe Enum Pattern Class that exports constants and

has no public constructor.

Advantages Fixes disadvantages of constants. Can add arbitrary methods and

fields to this enum class. Can implement interfaces.

Java Collection

Transparency No. 71

Disadvantages of Typesafe Enum Pattern

Verbose Error prone Can’t be used in switch statements. Problems with Serialization.

readResolve() method required.

Wouldn’t it be nice if the compiler would take care of enums for you?

Java Collection

Transparency No. 72

The New Typesafe Enum Construct

Compiler support for Typesafe Enum pattern. Looks like the traditional enum in C. Far more powerful

All the advantages of Typesafe Enum pattern Allows programmers to add arbitrary methods and fields.

Can be used in switch statements. No problem with Serializing enums.

Serializes constants, not values.

Java Collection

Transparency No. 73

Simple example of Typesafe enum Construct

For a deck of cards…

enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

enum Rank { DUECE, THREE, FOUR, FIVE, SIX,

SEVEN, EIGHT, NINE, TEN,

JACK, QUEEN, KING, ACE }

List<Card> deck = new ArrayList<Card>();

for ( Suit s: Suit.values() )

for ( Rank r: Rank.values() )

deck.add(new Card(s,r));

Java Collection

Transparency No. 74

A more complex Typesafe enum Construct

public enum OperationEnum { QUOTE(1), ISSUE(2), RENEW(4), CANCEL(12), ENDORSE(16), CHANGE(64), REINSTATE(192);

private int operation = 0; private OperationEnum(int op) { this.operation = op; } public boolean isNewOperation() { return (this.operation==2) || (this.operation==4) || (this.operation==192); }}

Java Collection

Transparency No. 75

Using the Typesafe enum Construct

void process(OperationEnum oper) {

. . .

switch (oper) {

case ISSUE: . . .

case CANCEL: . . .

}

// Prints “ISSUE”, not “1”

System.out.println(oper);

}

Java Collection

Transparency No. 76

Enumeration Type

Enum <E extends Enum<E>>

name() : String ;

ordinal() : int ;

# Enum(String, int ) ;

toString() = { return name ;}

equals(E o) = { return this == 0 ;}

hashCode() = { return super.hashCode() ; }

+comparedTo(E o) : int ; // by ordinal

+getDeclaringClass() : Class<E> // subclass of Enum

+ valueOf(Class<T> enumType, String name) : T

enum Season { SPRING(“S”), …. }

Java Collection

Transparency No. 77

public enum Season { SPRING(“warm”), SUMMER(“hot”), FALL(“cool”), WINTER(“cold”);

String temperature ; // additional methods or fields permitted!!

private Season(String s ) { temperature = s ;} /* real story private Season(String name, int ord, String s ) { super(name, ord); temperature = s ; }*//* real storypublic static final Season = new Season(“SPRING”, 0, “warm”) ; … ; public static Season[] values = new Season[] { SPRING, …, WINTER }; public static Season[] values() { return values ;}*/}

Java Collection

Transparency No. 78

Program Annotation Facility

Annotate methods, fields, classes. Prefix annotations with “@”

Does not affect semantics of the program. Prior to the program annotation facility

@depreciated JavaDoc tag– deprecated status of API methods

transient modifier– queried to determine serializable status of a field

Java Collection

Transparency No. 79

Program Annotation Facility Example

@remote

@revised(“04/20/2006”)public Task getTask(Student s);

@persist private int idNum;

Note: method getTask(Student)meaning not affected

by the annotations @remote and @Date. field idNum semantics not affected by annotation @persist.

Java Collection

Transparency No. 80

Program Annotation Facility Uses

Development/deployments tools can use annotations to process them in some fashion. @remote could indicate a remote method that can be invoked

remotely. @persist could indicate a field that must be persisted. @column could indicate the database column that a field must be

persisted to.

Expect to see a lot of use for this facility in the future by vendors.

Java Collection

Transparency No. 81

Terminology about generic classes

A class/interface is generic if it declares one or more type variables (§4.4).

These type variables are known as the type parameters of the class.

The type parameter section follows the class name and is delimited by angle brackets. It defines one or more type variables that act as parameters.

A generic class declaration defines a set of parameterized types, one for each possible invocation

of the type parameter section. All of these parameterized types share the same class at runtime.

Java Collection

Transparency No. 82

Type paramters

TypeParameters : < TypeParameterList > TypeParameterList : TypeParameter + TypeParameter: TypeVariable TypeBound?

TypeBound: extends ClassOrInterfaceType AdditionalBound*

AdditionalBound: & InterfaceType

Java Collection

Transparency No. 83

Example

Examples: pubic class Vector <T> { … } public interface Map<K, V> { … }

class Vector and Map are both generic types since. Vector declares one type variable/parameter: T Map declares two type variables/parameters: K and V.

The followings are parameterized types defined by Vector/Map Vector<String> x = new Vector<String> (); Vector<Integer> y = new Vector<Integer> (); boolean b = x.getClass() == y.getClass(); Map<String, Integer> map ;

Java Collection

Transparency No. 84

Mutually recursive type variable bounds

interface ConvertibleTo<T> { T convert(); }

class ReprChange<T implements ConvertibleTo<S>,

S implements ConvertibleTo<T> > {

T t;

void set(S s) { t = s.convert(); }

S get() { return t.convert(); }

}