Lecture 10/11 : Java Generics and Collections Some features in new - - PowerPoint PPT Presentation

lecture 10 11 java generics and collections
SMART_READER_LITE
LIVE PREVIEW

Lecture 10/11 : Java Generics and Collections Some features in new - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

CS6202 Java Generics 1

CS6202: Advanced Topics in Programming Languages and Systems Lecture 10/11 : Java Generics and Collections

  • 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 2

Motivation Motivation

Generics is important for: software reuse type safety

  • ptimization (fewer castings)

Important Principle : “Everything should be as simple as possible but no simpler”

CS6202 Java Generics 3

Java 5 Java 5

Some features in new language boxing/unboxing new form of loop functions with variable number of arguments generics more concurrency features

CS6202 Java Generics 4

Java 5 : Example Java 5 : Example

generic collection unboxing/boxing new loop function with variable number of arguments assert from Java 1.4

slide-2
SLIDE 2

CS6202 Java Generics 5

Example in Java 1.4 Example in Java 1.4

similar code with Array in Java 1.4

CS6202 Java Generics 6

Generics by Erasure Generics by Erasure

Java Generics is implemented by erasure:

  • simplicity
  • small
  • eases evolution (compatibility)

List<Integer>, List<String>, List<List<String>>

erases to just List 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 7

Boxing and Boxing and Unboxing Unboxing

Unboxed types can give better performance Boxed type may be cached for frequent values.

60% slower

CS6202 Java Generics 8

Foreach Foreach Loop Loop

Works with iterator and is more concise. Kept simple – cannot use remove + multiple lists.

compiles to

slide-3
SLIDE 3

CS6202 Java Generics 9

Iterator/Iterable Iterator/Iterable Interfaces Interfaces

Iterator supports iteration through a collection. Iterable allows an Iterator object to be build.

CS6202 Java Generics 10

Methods with Methods with Varargs Varargs

Packing argument for array is cumbersome. Arrays can be used to accept a list of elements.

CS6202 Java Generics 11

Methods with Methods with Varargs Varargs

Syntactic sugar to support Varargs.

varargs

The above is compiled to use array.

CS6202 Java Generics 12

Outline

  • 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
slide-4
SLIDE 4

CS6202 Java Generics 13

Subtyping Subtyping and Substitutions Principle and Substitutions Principle

Subtyping Principle : A variable of a given type may be assigned a value of any subtype of that type. The same applies to arguments. However, it is not sound to have:

List<Integer> <: List<Number>

But arrays may be covariant:

Integer[] <: Number[]

CS6202 Java Generics 14

Covariant and Covariant and Contravariant Contravariant Subtyping Subtyping

Covariant Subtyping :

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 Get and Put Principle : use an extends wildcard when you

  • nly 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 15

Example Example

Copy from one list to another : Getting elements :

CS6202 Java Generics 16

Example Example

Putting elements : Two Bounds? Not legal though plausible.

slide-5
SLIDE 5

CS6202 Java Generics 17

Arrays Arrays

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 18

Wildcard Wildcard vs vs T ype Parameter T ype Parameter

Wildcards may be used if only Objects are being read.

Collection<?> also stands for Collection<? extends Object>

Alternative (more restrictive but safer).

CS6202 Java Generics 19

Wildcard Capture Wildcard Capture

We can reverse a list using parametric type or wildcard type?

CS6202 Java Generics 20

Wildcard Capture Wildcard Capture

Solution is to use a wrapper function with wildcard capture : This solution is similar to a open/close capture of an existential type.

slide-6
SLIDE 6

CS6202 Java Generics 21

Restriction on Wildcards Restriction on Wildcards

Wildcards should not appear at (i) top-level of class instance creation (ii) explicit type parameters of generic method (iii) in supertypes of extends/implements

CS6202 Java Generics 22

Restriction on Wildcards Restriction on Wildcards

Restriction on supertype of extends/implements Restriction on explicit parameter of methods permitted

CS6202 Java Generics 23

Outline

  • 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 24

Comparison and Bounds Comparison and Bounds

x.compareTo(y) method is based on natural ordering x less_than y returns a negative value x equal_to y returns zero x more_than y returns a positive value

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

slide-7
SLIDE 7

CS6202 Java Generics 25

Contract for Comparable Contract for Comparable

Anti-symmetric :

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 forall z. sgn(x.compareTo(z)==sgn(x.compareTo(z))

CS6202 Java Generics 26

Implementing Integer as Comparable Implementing Integer as Comparable

Correct way : Incorrect way - overflow problem :

CS6202 Java Generics 27

Maximum of a Collection Maximum of a Collection

Generic code to find maximum : A more general signature is based on get/put principle:

need to compare with its own type

CS6202 Java Generics 28

Fruity Example Fruity Example

There is some control over what can be compared.

cannot compare apple with orange can now compare between orange/apple

slide-8
SLIDE 8

CS6202 Java Generics 29

Fruity Example Fruity Example

Recall : This works for List<Orange> and List<Fruit>, but old version works for only List<Fruit> .

CS6202 Java Generics 30

Comparator Comparator

Allows additional ad-hoc ordering to be specified : Example : shorter string is smaller

CS6202 Java Generics 31

Comparator Comparator

Implement max using Comparator : Comparator from natural order :

CS6202 Java Generics 32

Enumerated T ypes Enumerated T ypes

Enumerated type corresponds to a class with a set of final static

  • values. First, an abstract class :

compare within same enumerated type only

slide-9
SLIDE 9

CS6202 Java Generics 33

Enumerated T ype Enumerated T ype

An instance of enumerated type.

CS6202 Java Generics 34

Covariant Overriding Covariant Overriding

Java 5 can override another if arguments match exactly but the result of overriding method is a subtype of other method. Useful for clone method :

class Object { : public Object clone() { … } } class Point { : public Point clone() { return new Point(x,y);} }

covariant overriding

CS6202 Java Generics 35

Outline

  • 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 36

Constructors Constructors

Actual type parameters should be provided :

Pair<String,Integer> p = new Pair<String,Integer>(“one”,2) Pair<String,Integer> p = new Pair(“one”,2)

If you forget, it is a raw type with unchecked warning :

slide-10
SLIDE 10

CS6202 Java Generics 37

Static Members Static Members

Static methods are independent of any type parameters :

Cell.getCount() // ok Cell<Integer>.getCount() // compile-time error Cell<?>.getCount() // compile-time error

CS6202 Java Generics 38

How Erasure Works How Erasure Works

CS6202 Java Generics 39

Outline

  • 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 40

Reification Reification

Refers to an ability to get run-time type information. This is a kind of concretization.

Number[] has reified type Number[] ArrayList<Number> has reified type ArrayList

Array is reified with its component type, but parameterized types is reified without its component type.

slide-11
SLIDE 11

CS6202 Java Generics 41

Reified Types Reified Types

Type that is reifiable. Type that is not reifiable.

CS6202 Java Generics 42

Reification Reification

An incorrect code to convert a collection to an array. not reifiable

CS6202 Java Generics 43

Reification Reification -

  • Arrays

Arrays

More problem :

CS6202 Java Generics 44

Reification Reification -

  • Arrays

Arrays

More problem :

slide-12
SLIDE 12

CS6202 Java Generics 45

Reification Reification -

  • Arrays

Arrays

Alternative using another array + reflection!

CS6202 Java Generics 46

Reification Reification -

  • Arrays

Arrays

Solution using a Class – runtime type!

CS6202 Java Generics 47

Reflection Reflection

Reflection is a term to allow a program to examine its own definition. Generics for reflection supports the process using new generic programming techniques. Reflection for generics allow generic types (e.g. type vars, wildcard types) to be captured at runtime.

CS6202 Java Generics 48

Generics for Reflection Generics for Reflection

A new generic type for Class

slide-13
SLIDE 13

CS6202 Java Generics 49

Reflection for Primitive Type Reflection for Primitive Type

We cannot use Class<int> as type parameter must be reference

  • type. Use Class<Integer> for int.class instead!

Java.lang.reflect.array.newInstances(int.class,size)

returns int[] and not Integer[] through a hack! However, int[].class is correctly denoted by Class<int[]>

CS6202 Java Generics 50

Generic Reflection Library Generic Reflection Library

newArray newArray

CS6202 Java Generics 51

Reflection for Generic Reflection for Generic

Non-generic reflection example : Output :

CS6202 Java Generics 52

Reflection for Generic Reflection for Generic

Generic reflection example : Output :

Bytecode contains generic type information!

slide-14
SLIDE 14

CS6202 Java Generics 53

Reflecting Generic T ypes Reflecting Generic T ypes

Type interface to describe generic type :