<<

Topics

• background and goals of • basics of generic classes = parameterized types • generic methods for general algorithms • inheritance rules for generic types Generic programming in Java • bounded type parameters • generic code and the Java Virtual Machine • restrictions and limitations • wildcard types and wildcard type capture

1 2

Why generic programming Why generic programming (cont.)

Background • generic types are a powerful tool to write reusable • old version 1.4 Java collections were Object-based object-oriented components and libraries and required the use of ugly casts • however, the generic language features are not easy – cannot specify the exact type of elements to master and can be misused – must cast to specific classes when accessing – their full understanding requires the knowledge of Java generics the of programming languages • lets you write code that is safer and easier to read • especially covariant and contravariant typing • is especially useful for general data structures, such • the following introduces the main aspects of Java as ArrayList generics and their use and limitations • we mostly inspect illustrative samples of what is and • generic programming = programming with classes what is not allowed, with some short glimpses inside and methods parameterized with types the JVM implementation 3 4

1 Why generic programming (cont.) Definition of a simple generic class

Java generics class Pair { public T first; • in principle, supports statically-typed data structures public T second; – early detection of type violations public Pair (T f, T s) { first = f; second = s; } • cannot insert a string into ArrayList public Pair () { first = null; second = null; } – also, hides automatically generated casts } • superficially resembles C++ templates • you instantiate the generic class by substituting – C++ templates are factories for ordinary classes actual types for type variables, as: Pair and functions • you can think the result as a class with a constructor • a new class is always instantiated for given public Pair (String f, String s), etc . . distinct generic parameters (type or other) • you can then use the instantiated generic class as it • in Java, generic types are factories for compile-time were a normal class (almost): entities related to types and methods Pair pair = new Pair ("1","2"); 5 6

Multiple type parameters allowed Generic static algorithms • you can define generic methods both inside ordinary • you can have multiple type parameters classes and inside generic classes

class Pair { class Algorithms { // some utility class public T first; public static T getMiddle (T [ ] a) { public U second; return a [ a.length / 2 ]; public Pair (T x, U y) { first = x; second = y; } } public Pair () { first = null; second = null; } . . . } } • to instantiate: Pair • when calling a generic method, you can specify type String s = Algorithms.getMiddle (names); • but in most cases, the compiler infers the type: String s = Algorithms. getMiddle (names); 7 8

2 Inheritance rules for generic types Comments on inheritance relations

• Pair matches Pair => subtype relation (covariant typing) • Pair matches Pair => subtype relation (contravariant typing) • Pair can contain only Employees, but Pair may be assigned anything (Numbers) => no subtype relation • also: Pair <= Pair <= Pair (raw) List sl = new LinkedList (); List x = sl; // OK x.add (new Integer (5)); // type safety warning . . String str = sl.get (0); // throws ClassCast. 9 10

Bounds for type variables (cont.) Bounds for type variables • consider the min algorithm: find the smallest item in • however, Comparable is itself a generic a given array of elements • moreover, any supertype of T may have extended it • to compile this, must restrict T to implement the public static > T min (T [ ] a) { . . . // the more general form public static T smallest = a [0]; T min (T [ ] a) { // this is almost correct for (int i = 1; i < a.length; i++) if (a.length == 0) throw new InvalidArg.. (..); if (smallest.compareTo (a [i]) > 0) // T constraint T smallest = a [0]; smallest = a [i]; for (int i = 1; i < a.length; i++) return smallest; if (smallest.compareTo (a [i]) > 0) // T constraint } smallest = a [i]; • cannot inherit multiple different instantiations of the return smallest; same generic type (class or interface) } 11 • an inherited generic type is fixed for subtypes, too12

3 Generic code and the JVM Generic code and the JVM (cont.) • the JVM has no instantiations of generic types • Pair and Pair use the same • a generic type definition is compiled once only, and bytecode generated as the raw class Pair a corresponding raw type is produced • when translating generic expressions, such as – the name of the raw type is the same name but Pair buddies = new Pair < . .; type variables removed Employee buddy = buddies.first; • type variables are erased and replaced by their • the compiler uses the raw class and automatically bounding types (or Object if no bounds); e.g.: inserts a cast from Object to Employee: class Pair { // the raw type for Pair Employee buddy = (Employee)buddies.first; public Object first; public Object second; – in C++, no such casts are required since class public Pair (Object f, Object s) { . . } instantiations already use specific types } • if multiple constraints (Object & Comparable. .) then • code has some generic info, but objects don't the type parameter is replaced by the first one 13 14

Overriding of methods of generic type Restrictions and limitations

• consider a generic class with a non-final method: • in Java, generic types are compile-time entities class Pair { // parameter T is erased from code – in C++, instantiations of a class are compiled separately as source code, and tailored public void setSecond (T s) { second = s; } . . code is produced for each one • to override such type-erased methods, the compiler must generate extra bridge methods: • primitive type parameters (Pair ) not allowed class DateInterval extends Pair { – in C++, both classes and primitive types allowed public void setSecond (Date high) { // override • objects in JVM have non-generic classes: if (high.compareTo (first) < 0) throw new . . Pair strPair = new Pair . .; second = high; // otherwise OK Pair numPair = new Pair . .; } b = strPair.getClass () == numPair.getClass (); public void setSecond (Object s) { // bridge method assert b == true; // both of the raw class Pair setSecond ((Date)s); // generated by compiler – but byte-code has reflective info about generics } . . 15 16

4 Restrictions and limitations (cont.) Wildcard types • instantiations of generic parameter T are not allowed • note that the raw class Pair is not equal Pair new T () // ERROR: whatever T to produce? Pair pair1 = . .; new T [10] pair1.first = new Double (10.0); // WARNING • arrays of parameterized types are not allowed Pair pair2 = . .; new Pair [10]; // ERROR pair2.first = new Double (10.0); // ERROR – since type erasure removes type information • but some operations have no type constraints: needed for checks of array assignments public static boolean hasNulls (Pair p) { • static fields and static methods with type parameters return p.first == null || p.second == null; are not allowed } class Singleton { • alternatively, you could provide a generic method private static T singleOne; // ERROR public static boolean hasNulls (Pair p) – since after type erasure, one class and one shared • generally, prefer wildcard types (but use generic static field for all instantiations and their objects method with type T when multiple parameters) 17 18

Wildcard capture Collections and algorithms • goal: design a minimal interface that you need • the wildcard type ? cannot be used as a declared type of any variables (as in the previous slide) • e.g., for max, implement to take any Collection Pair p = new Pair ("one", "two"); . . public static > T max (Collection c) { • but, can sometimes use a generic method to // a hypothetical implementation: capture the wildcard: Iterator it = c.iterator (); public static void rotate (Pair p) { T largest = it.next (); // or throws NoSuchElement T temp = p.first; p.first = p.second; while (it.hasNext ()) { p.second = temp; T val = it.next (); } if (largest.compareTo (val) < 0) largest = val; } • the compile checks that such a capture is legal return largest; – e.g., the context ensures that T is unambiguous }

19 20

5