Java 5 New Features 11 Feb22 New features

Java 5 New Features 11 -Feb-22

New features (Not all) n Generics n n Enhanced for loop n n Provides all the well-known benefits of the Typesafe Enum pattern Static import n n Avoids manual conversion between primitive types (such as int) and wrapper types (such as Integer) Typesafe enums n n Eliminates the drudgery and error-proneness of iterators Autoboxing/unboxing n n Compile-time type safety for collections without casting Lets you avoid qualifying static members with class names Metadata n n Tools to generate boilerplate code from annotations in the source code Leads to a "declarative" programming style where the programmer says what should be done and tools emit the code to do it

Enhanced for loop n Instead of void cancel. All(Collection c) { for (Iterator i = c. iterator(); i. has. Next(); ) { Timer. Task tt = (Timer. Task) i. next(); tt. cancel(); } } n You will be able to use: void cancel. All(Collection c) { for (Object o : c) ((Timer. Task)o). cancel(); } n Or: void cancel. All(Collection<Timer. Task> c) { for (Timer. Task task : c) task. cancel(); } n Not everyone likes this syntax!

Compiler Sugar n Compiler helps you n n n That is, you can key in less words But it does not actually extend the power of the language itself! Many new features are provided by compiler sugars, but not all!

Generics n n A generic is a method that is recompiled with different types as the need arises The bad news: n n n Instead of saying: List words = new Array. List(); You'll have to say: List<String> words = new Array. List<String>(); n List<Object> words = new Array. List<String>(); is NOT allowed. The good news: n n Provides compile-time checking to make sure you are using the correct type No casting; instead of String title = ((String) words. get(i)). to. Uppercase(); you use String title = words. get(i). to. Uppercase();

Differences in API docs n See API document n Vector in 1. 4 n n http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/util/Vector. html Vector in 1. 5 n http: //java. sun. com/j 2 se/1. 5. 0/docs/api/java/util/Vector. html

Implementing Generics class/interface List<E> { void add(E x); Iterator<E> iterator(); } interface Iterator<E> { E next(); boolean has. Next(); } class Linked. List<E> implements List<E> { // implementation }

Implementing Generics (cont’d) class Some. Class<T extends Super. Some. Class> { … } //Constraint on T

Wildcards public void print. Collection(Collection c) { Iterator i = c. iterator(); for(int k = 0; k<c. size(); k++) { System. out. println(i. next()); } } void print. Collection(Collection<? > c) { for(Object o: c) { System. out. println(o); } }

Wildcards accessing void print. Collection(Collection<? > c) { c. add(new Object()); //compile-time error, how to fix it? } Note that the difference between getting and putting

Wildcards and Inheritance List<Square> list = new List<Square>; as the passed argument. public void draw(List<Shape> shape) { //wrong, why? for(Shape s: shape) { s. draw(this); } } public void draw(List<? extends Shape> shape) { for(Shape s: shape) { s. draw(this); } }

Wildcards and Inheritance (cont’d) public void add. Rectangle(List<? extends Shape> shape) { shape. add(new Rectangle()); //compile-time error, why? }

More Wildcards Array. List<? > words = new Array. List<String>(); //OK?

Several Wildcards n "? extends Type“ n n n "? super Type“ n n Denotes a family of subtypes of type Type. This is the most useful wildcard Denotes a family of supertypes of type Type "? “ n Denotes the set of all types or any
![Generic Method static void from. Array. To. Collection(Object[] a, Collection<? > c) { for Generic Method static void from. Array. To. Collection(Object[] a, Collection<? > c) { for](http://slidetodoc.com/presentation_image_h2/abe169d275fda3dbd9c5d75f4bc3f93f/image-15.jpg)
Generic Method static void from. Array. To. Collection(Object[] a, Collection<? > c) { for (Object o : a) { c. add(o); // compile time error } } //Generic Method static <T> void from. Array. To. Collection(T[] a, Collection<T> c) { for (T o : a) { c. add(o); // correct } }

Differences from Template in C++ n n n Generics simply provide compile-time type safety and eliminate the need for casts. The compiler keeps track of the generics internally, and all instances use the same class file at compile/run time. A C++ template is just a fancy macro processor n whenever a template class is instantiated with a new class, the entire code for the class is reproduced and recompiled for the new class.

Autoboxing n n n Java won’t let you use a primitive value where an object is required--you need a “wrapper” Similarly, you can’t use an object where a primitive is required--you need to “unwrap” it Java 1. 5 makes this automatic: n Map<String, Integer> m = new Tree. Map<String, Integer>(); for (String word : args) { m. put(word, m. get(word) + 1); }

Enumerations n n An enumeration, or “enum, ” is simply a set of constants to represent various values Here’s the old way of doing it n n n public final int int SPRING = 0; SUMMER = 1; FALL = 2; WINTER = 3; This is a nuisance, and is error prone as well Here’s the new way of doing it: n enum Season { winter, spring, summer, fall }

Advantages of the new enum n They provide compile-time type safety n n They're robust n n n int enums are compiled into clients, and you have to recompile clients if you add, remove, or reorder constants. Printed values are informative n n Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense). If you print an int enum you just see a number. Because they're objects, you can put them in collections. Because they're essentially classes, you can add arbitrary fields and methods n It can be used in switch cases

New features of enum n public enum Coin { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); Coin(int value) { this. value = value; } private final int value; public int value() { return value; } }

Another Interesting Example public enum Operation { PLUS { double eval(double x, double y) { return x + y; } }, MINUS { double eval(double x, double y) { return x - y; } }, TIMES { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x, double y); }
![public static void main(String args[]) { double x = Double. parse. Double(args[0]); double y public static void main(String args[]) { double x = Double. parse. Double(args[0]); double y](http://slidetodoc.com/presentation_image_h2/abe169d275fda3dbd9c5d75f4bc3f93f/image-22.jpg)
public static void main(String args[]) { double x = Double. parse. Double(args[0]); double y = Double. parse. Double(args[1]); for (Operation op : Operation. values()) System. out. printf("%f %s %f = %f%n", x, op, y, op. eval(x, y)); } $ java Operation 4 2 4. 000000 PLUS 2. 000000 = 6. 000000 4. 000000 MINUS 2. 000000 = 2. 000000 4. 000000 TIMES 2. 000000 = 8. 000000 4. 000000 DIVIDE 2. 000000 = 2. 000000 怎麼改成印+-*/

Another way public enum Operation { PLUS, MINUS, TIMES, DIVIDE; // Do arithmetic op represented by this constant double eval(double x, double y){ switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } throw new Assertion. Error("Unknown op: " + this); } }

Static import facility import static java. lang. System. out; public class Test { public static void main(String. . . args) { out. println("hello world"); } } n You no longer have to say System. out. println

scanf & printf Scanner sc = new Scanner(System. in); int i = sc. next. Int(); String name = sc. next(); System. out. printf("[%s]我今年%d歲", "popcorny", 18); String str = String. format("[%s]屁啦~", "moliwang");
![Variable length parameters n n public static void main(String[] args) public static void main(String… Variable length parameters n n public static void main(String[] args) public static void main(String…](http://slidetodoc.com/presentation_image_h2/abe169d275fda3dbd9c5d75f4bc3f93f/image-26.jpg)
Variable length parameters n n public static void main(String[] args) public static void main(String… args)

Metadata n n n @Override To guarantee you “override” a method. That is, typo is not possible There are many other useful Metadata

Reference n n n http: //java. sun. com/j 2 se/1. 5. 0/docs/relnotes/features. html (All new features, hard) http: //java. sun. com/developer/technical. Articles/J 2 SE/generics/ http: //www. cs. indiana. edu/classes/jett/sstamm/
- Slides: 28