CS6202: Advanced Topics in Programming Languages Java 5 Java 5 and Systems Lecture 10/11 : Java Generics and Collections Some features in new language boxing/unboxing • Overview • Subtyping and Wildcard new form of loop • Comparison and Bounds • Declaration and Erasure functions with variable number of arguments • Reification and Reflection • Collections generics • Iterator, Iterable, Collection • Set, Queues, List, Maps more concurrency features • Design Patterns • Other Issues CS6202 Java Generics 1 CS6202 Java Generics 3 Motivation Motivation Java 5 : Example Java 5 : Example Generics is important for: unboxing/boxing generic collection software reuse type safety new optimization (fewer castings) loop Important Principle : “Everything should be as simple as possible but no simpler” function with variable number of arguments assert from Java 1.4 CS6202 Java Generics 2 CS6202 Java Generics 4
Example in Java 1.4 Example in Java 1.4 Boxing and Unboxing Boxing and Unboxing Unboxed types can give better performance Boxed type may be cached for frequent values. 60% slower similar code with Array in Java 1.4 CS6202 Java Generics 5 CS6202 Java Generics 7 Generics by Erasure Generics by Erasure Foreach Loop Foreach Loop Works with iterator and is more concise. Java Generics is implemented by erasure: Kept simple – cannot use remove + multiple lists. - simplicity - small - eases evolution (compatibility) List<Integer>, List<String>, List<List<String>> erases to just List compiles to Anomaly : array type very different from parametric type. new String[size] new ArrayList<String>() with the latter losing info on element type. CS6202 Java Generics 6 CS6202 Java Generics 8
Iterator/Iterable Interfaces Iterator/Iterable Interfaces Methods with Methods with Varargs Varargs Iterator supports iteration through a collection. Syntactic sugar to support Varargs. varargs Iterable allows an Iterator object to be build. The above is compiled to use array. CS6202 Java Generics 9 CS6202 Java Generics 11 Methods with Varargs Methods with Varargs Outline Arrays can be used to accept a list of elements. • Overview • Subtyping and Wildcard • Comparison and Bounds • Declaration and Erasure • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns Packing argument for array is cumbersome. • Other Issues CS6202 Java Generics 10 CS6202 Java Generics 12
Subtyping and Substitutions Principle Subtyping and Substitutions Principle Example Example Copy from one list to another : Subtyping Principle : A variable of a given type may be assigned a value of any subtype of that type. The same applies to arguments. Getting elements : However, it is not sound to have: List<Integer> <: List<Number> But arrays may be covariant: Integer[] <: Number[] CS6202 Java Generics 13 CS6202 Java Generics 15 Covariant and Contravariant Covariant and Contravariant Subtyping Subtyping Example Example Covariant Subtyping : Putting elements : List<Integer> <: List<? extends Number> list of elements of any type that is a subtype of Number Contravariant Subtyping : List<Number> <: List<? super Integer> list of elements of any type that is a supertype of Number Two Bounds? Not legal though plausible. Get and Put Principle : use an extends wildcard when you only get values out of a structure, use a super wildcard when you put values into a structure. Don’t use wildcard when you both get and put. CS6202 Java Generics 14 CS6202 Java Generics 16
Arrays Arrays Wildcard Capture Wildcard Capture We can reverse a list using parametric type or wildcard type? Array subtyping is covariant. This was designed before generics. Seems irrelevant now : - unsound as it relies on runtime checks - incompatible with Collection - should perhaps deprecate over time. One Solution : Use more of Collection rather than Array - more flexibility - more features/operations - better generics CS6202 Java Generics 17 CS6202 Java Generics 19 Wildcard vs Wildcard vs T T ype Parameter ype Parameter Wildcard Capture Wildcard Capture Wildcards may be used if only Objects are being read. Solution is to use a wrapper function with wildcard capture : Collection<?> also stands for Collection<? extends Object> Alternative (more restrictive but safer). This solution is similar to a open/close capture of an existential type. CS6202 Java Generics 18 CS6202 Java Generics 20
Restriction on Wildcards Restriction on Wildcards Outline Wildcards should not appear at (i) top-level of class instance creation • Overview (ii) explicit type parameters of generic method • Subtyping and Wildcard (iii) in supertypes of extends/implements • Comparison and Bounds • Declaration and Erasure • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns • Other Issues CS6202 Java Generics 21 CS6202 Java Generics 23 Restriction on Wildcards Restriction on Wildcards Comparison and Bounds Comparison and Bounds x.compareTo(y) method is based on natural ordering Restriction on supertype of extends/implements x less_than y returns a negative value x equal_to y returns zero x more_than y returns a positive value Restriction on explicit parameter of methods Consistency with equal x.equals(y) if and only if x.compareTo(y)==0 Main difference with null x.equals(null) returns false x.compareTo(null) throws an exception permitted CS6202 Java Generics 22 CS6202 Java Generics 24
Contract for Comparable Contract for Comparable Maximum of a Collection Maximum of a Collection Generic code to find maximum : need to compare Anti-symmetric : with its own type sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) Transitivity : if x.compareTo(y)<0 and y.compareTo( z )<0 then x.compareTo( z )<0 Congruence : if x.compareTo(y)==0 then A more general signature is based on get/put principle: forall z. sgn(x.compareTo(z)==sgn(x.compareTo(z)) CS6202 Java Generics 25 CS6202 Java Generics 27 Implementing Integer as Comparable Implementing Integer as Comparable Fruity Example Fruity Example Correct way : There is some control over what can be compared. cannot compare apple with orange Incorrect way - overflow problem : can now compare between orange/apple CS6202 Java Generics 26 CS6202 Java Generics 28
Fruity Example Fruity Example Comparator Comparator Recall : Implement max using Comparator : This works for List<Orange> and List<Fruit> , but old version works for only List<Fruit> . Comparator from natural order : CS6202 Java Generics 29 CS6202 Java Generics 31 Comparator Comparator Enumerated T Enumerated T ypes ypes Allows additional ad-hoc ordering to be specified : Enumerated type corresponds to a class with a set of final static values. First, an abstract class : Example : shorter string is smaller compare within same enumerated type only CS6202 Java Generics 30 CS6202 Java Generics 32
Enumerated T Enumerated T ype ype Outline An instance of enumerated type. • Overview • Subtyping and Wildcard • Comparison and Bounds • Declaration and Erasure • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns • Other Issues CS6202 Java Generics 33 CS6202 Java Generics 35 Covariant Overriding Covariant Overriding Constructors Constructors Java 5 can override another if arguments match exactly but the Actual type parameters should be provided : result of overriding method is a subtype of other method. Pair<String,Integer> p = new Useful for clone method : Pair<String,Integer>(“one”,2) class Object { : public Object clone() { … } If you forget, it is a raw type with unchecked warning : } class Point { Pair<String,Integer> p = new Pair(“one”,2) : public Point clone() { return new Point(x,y);} } covariant overriding CS6202 Java Generics 34 CS6202 Java Generics 36
Static Members Static Members Outline Static methods are independent of any type parameters : • Overview • Subtyping and Wildcard Cell.getCount() // ok • Comparison and Bounds Cell<Integer>.getCount() // compile-time error • Declaration and Erasure • Reification and Reflection Cell<?>.getCount() // compile-time error • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns • Other Issues CS6202 Java Generics 37 CS6202 Java Generics 39 How Erasure Works How Erasure Works Reification Reification Refers to an ability to get run-time type information. This is a kind of concretization. Array is reified with its component type, but parameterized types is reified without its component type. Number[] has reified type Number[] ArrayList<Number> has reified type ArrayList CS6202 Java Generics 38 CS6202 Java Generics 40
Reified Types Reified Types Reification - Reification - Arrays Arrays Type that is reifiable. More problem : Type that is not reifiable. CS6202 Java Generics 41 CS6202 Java Generics 43 Reification Reification Reification - Reification - Arrays Arrays An incorrect code to convert a collection to an array. More problem : not reifiable CS6202 Java Generics 42 CS6202 Java Generics 44
Recommend
More recommend