Java 5 New Features v v v Generics

  • Slides: 12
Download presentation
Java 5 New Features v v v Generics Enhanced for loop Autoboxing/unboxing Typesafe enums

Java 5 New Features v v v Generics Enhanced for loop Autoboxing/unboxing Typesafe enums Other q q q Varargs Static Import Metadata New classes and methods VM Enhancements Comp. Sci 100 E 40. 1

Generics v v v Allows classes to store objects whose type is irrelevant to

Generics v v v Allows classes to store objects whose type is irrelevant to storing class, while allowing type-safe retrieval E. g. , Collection Syntax Array. List<String> list = new Array. List<String>(); list. put(“hello”); // put() takes a String Iterator<String> iter = list. iterator(); String s = iter. next(); // next() returns a String v Compare with earlier Java Array. List list = new Array. List(); list. put(“hello”); // put() takes an Object Iterator iter = list. iterator(); String s = (String)iter. next(); // next() returns an Object which must be cast to String Comp. Sci 100 E 40. 2

Generics in API Docs v In API documentation, generics are given a type alias,

Generics in API Docs v In API documentation, generics are given a type alias, e. g. , “E”: q q v Alias is arbitrary, but stands for the same type throughout class definition Can be on more than one type using different aliases Examples q q Class Array. List<E> o add(E o) o E get(int index) Interface Map<K, V> o V put(K key, V value) o V get(Object key) o Collection<V> values() Comp. Sci 100 E 40. 3

Enhanced for Loop v Replaced iterators, indexing v Iterators and indexing are prone to

Enhanced for Loop v Replaced iterators, indexing v Iterators and indexing are prone to bounds errors // throws Array. Index. Out. Of. Bounds. Exception for (int i = 0; i <= arr. length; i++) { System. out. println(arr[i]); } // what does this do? Iterator iter = list. iterator(); while (iter. has. Next()) { if (!“stop”. equals(iter. next())) { System. out. println(iter. next()); } } Comp. Sci 100 E 40. 4

Looping in Java 5 v Java 5 introduces new language syntax for looping over

Looping in Java 5 v Java 5 introduces new language syntax for looping over arrays and collections using for (aka “For-Each” loop) v Syntax: for (type var: collection) { // do something with var } v Examples: void process. Array(String[] arr) { for (String s: arr) System. out. println(s. to. Upper. Case()); } // generics work with new for loop to simplify syntax! void process. List(List<String> list) { for (String s: list) System. out. println(s); } Comp. Sci 100 E 40. 5

Autoboxing/Unboxing v Java primitive types provided for performance, but mix poorly with objects: //

Autoboxing/Unboxing v Java primitive types provided for performance, but mix poorly with objects: // compilation error! Array. List list = new Array. List(); list. add(42); int x = (int) list. get(0); // Kludgey fix provided by original Java: ugh! list. add(new Integer(42)); int x = ((Integer)list. get(0)). int. Value() v Java 5 automatically “boxes” primitive types in Object types as neeeded: Integer obj. Int; obj. Int = 42; // equivalent to obj. Int = new Integer(42); Comp. Sci 100 E 40. 6

Autoboxing with Generics and For-Each v Note again how the new Java 5 features

Autoboxing with Generics and For-Each v Note again how the new Java 5 features work together: // old syntax Integer sum. Integer(List list) { int sum = 0; Iterator iter = list. iterator(); while (iter. has. Next()) { Integer iobj = (Integer) iter. next(); sum += iobj. int. Value(); } } return new Integer(sum); // new syntax Integer sum. Integers(List<Integer> list) { int sum = 0; for (int x: list) sum+= x; // auto-unboxing elements return sum; // autobox return value } Comp. Sci 100 E 40. 7

New Features: Limitations v Generics are not everywhere, yet q consider list. to. Array()

New Features: Limitations v Generics are not everywhere, yet q consider list. to. Array() returning Object[] v Enhanced for loop on non-parameterized collections is still annoying (obviously using generics helps, but what if you are forced to use legacy code? ) q v for (Object o: list) { String s = (String)o; . . . } For loop doesn't give you a good way to loop over multiple collections in parallel: q still must do: int[] arr 1, arr 2; for (int i; i < arr 1. length; i++) { int x = arr 1[i] + arr 2[i]; } Comp. Sci 100 E 40. 8

New Features: Limitations (con't) v Autoboxing doesn't carry over to arrays, or to converting

New Features: Limitations (con't) v Autoboxing doesn't carry over to arrays, or to converting arrays to lists and vice versa: q can't do the following: int[] arr = new int[100]; Integer[] arr. Ints = arr; List<Integer> list = new Array. List<Integer>(); list. add. All(arr); Comp. Sci 100 E 40. 9

Typesafe Enums v Enums are a safer alternative to constants q Old way: public

Typesafe Enums v Enums are a safer alternative to constants q Old way: public static final int GO = 0; public static final int STOP = 1; public static final int YIELD = 2; . . q Consider code taking these values as a parameter: void process(int status) { if (status == GO). . . if (status == STOP). . . if (status == YIELD). . . else. . . // what does status == 10 mean? Comp. Sci 100 E 40. 10

The Enum Alternative v v v Enums define a type, just like a class

The Enum Alternative v v v Enums define a type, just like a class or primitive type Enums are not interchangeable with ints, impossible to get undefined values Enums can be enumerated using for String representations of enums actually mean something Examples: public enum Traffic. Light { GO, STOP, YIELD } public Traffic. Light my. Light = STOP; for (Traffic. Light t: Traffic. Light. values()) { System. out. print(t); System. out. print(“ “); } // output: GO STOP YIELD Comp. Sci 100 E 40. 11

Other New Features v Java 5 has many other new features, including: q Varargs

Other New Features v Java 5 has many other new features, including: q Varargs – variable-size argument lists for methods q Static Import – import constants, e. g. Math. PI q Metadata – attach extra information about code q New classes and methods – Queue, Scanner, printf, etc. q VM Enhancements Comp. Sci 100 E 40. 12