Chapter 21 Generics

36
Chapter 21 Generics 1

description

Chapter 21 Generics. Generics - Overview. Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse with compile-time type safety. What is Generics?. Generics is the capability to parameterize types. - PowerPoint PPT Presentation

Transcript of Chapter 21 Generics

Page 1: Chapter 21 Generics

Chapter 21 Generics

1

Page 2: Chapter 21 Generics

Generics - Overview

•Generic Methods specify a set of related methods

•Generic classes specify a set of related types

•Software reuse with compile-time type safety

2

Page 3: Chapter 21 Generics

What is Generics?

• Generics is the capability to parameterize types.

• Can define class or method with generic types

• Compiler substitutes with concrete types. • Example:

▫ a generic stack class that stores elements of a generic type.

▫ Can create stack of strings and stack of numbers.

▫ String and Number are concrete types.

3

Page 4: Chapter 21 Generics

Generic Methods

•Method overloading – can have several identical methods with same number of arguments, but of different types (printArray for Integer, Double, Character)

•Can replace with one generic method

4

Page 5: Chapter 21 Generics

Generic Methods

•Syntax:Public static <E> void print (E[] list)

Type parameter section in angle brackets before return type of method

Can be comma separated list.

5

Page 6: Chapter 21 Generics

Generic Methods6

public static <E> void print(E[] list) {

for (int i = 0; i < list.length; i++)

System.out.print(list[i] + " ");

System.out.println();

}

public static void print(Object[] list) {

for (int i = 0; i < list.length; i++)

System.out.print(list[i] + " ");

System.out.println();

}

Page 7: Chapter 21 Generics

Generic Methods

Generic methods can be defined in ordinary classes.

7

public class ArrayAlg{

public static <T> T getMiddle(T[] a) {

return a[a.length/2];

}

}

Page 8: Chapter 21 Generics

Pre-JDK 1.5

•Generics introduced in JDK 1.5•Prior versions of Java used inheritance•Parameters can be of type Object

8

Page 9: Chapter 21 Generics

Why Generics?

•What was wrong with using Object?▫Casting is necessary when return value is

of general typeAND▫No error checking - the type of object can

keep changing.

9

Page 10: Chapter 21 Generics

Why Generics?

• Key benefit: generics enable errors to be detected at compile time rather than at runtime.

• With generic class or method, can specify types of objects that the class or method may work with.

• Attempt to use class or method with incompatible object -> compilation error.

10

Page 11: Chapter 21 Generics

Generic Type11

package java.lang; public interface Comparable { public int compareTo(Object o)

}

package java.lang; public interface Comaprable<T> { public int compareTo(T o)

}

(a) Prior to JDK 1.5 (b) JDK 1.5

Generic Instantiation Runtime error

Compile error

Comparable c = new Date(); System.out.println(c.compareTo("red"));

(a) Prior to JDK 1.5

Comparable<Date> c = new Date(); System.out.println(c.compareTo("red"));

(b) JDK 1.5

Improves reliability

Page 12: Chapter 21 Generics

Why Do You Get a Warning?

public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); list.add("Java Programming"); }}

12

JDK 1.5 generics. (Types may not be compatible.)

Page 13: Chapter 21 Generics

Fix the Warning

public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList<String> list = new java.util.ArrayList<String>(); list.add("Java Programming"); }}

13

No compile warning on this line.

`

Page 14: Chapter 21 Generics

Generic ArrayList in JDK 1.514

java.util.ArrayList

+ArrayList()

+add(o: Object) : void

+add(index: int, o: Object) : void

+clear(): void

+contains(o: Object): boolean

+get(index: int) : Object

+indexOf(o: Object) : int

+isEmpty(): boolean

+lastIndexOf(o: Object) : int

+remove(o: Object): boolean

+size(): int

+remove(index: int) : boolean

+set(index: int, o: Object) : Object

java.util.ArrayList<E>

+ArrayList()

+add(o: E) : void

+add(index: int, o: E) : void

+clear(): void

+contains(o: Object): boolean

+get(index: int) : E

+indexOf(o: Object) : int

+isEmpty(): boolean

+lastIndexOf(o: Object) : int

+remove(o: Object): boolean

+size(): int

+remove(index: int) : boolean

+set(index: int, o: E) : E

(a) ArrayList before JDK 1.5 (b) ArrayList in JDK 1.5

Page 15: Chapter 21 Generics

No Casting NeededArrayList<Double> list = new ArrayList<Double>();list.add(5.5); // 5.5 is automatically converted to new Double(5.5)list.add(3.0); // 3.0 is automatically converted to new Double(3.0)Double doubleObject = list.get(0); // No casting is neededdouble d = list.get(1); // Automatically converted to double

15

Page 16: Chapter 21 Generics

Declaring Generic Classes and Interfaces

16

GenericStackGenericStack

GenericStack<E> -list: java.util.ArrayList<E>

+GenericStack()

+getSize(): int

+peek(): E

+pop(): E

+push(o: E): E

+isEmpty(): boolean

Creates an empty stack.

Returns the number of elements in this stack.

Returns the top element in this stack.

Returns and removes the top element in this stack.

Adds a new element to the top of this stack.

Returns true if the stack is empty.

An array list to store elements.

Page 17: Chapter 21 Generics

Bounded Generic Type

Syntax:<E extends BoundingType>

•Use keyword extends.•Both E and BoundingType can be a class

or interface.•Separate several bounds with & •(comma separates type variables)

17

Page 18: Chapter 21 Generics

Bounded Generic Type18

public static void main(String[] args ) {

Rectangle rectangle = new Rectangle(2, 2);

Circle9 circle = new Circle9(2);

System.out.println("Same area? " + equalArea(rectangle, circle));

}

public static <E extends GeometricObject> boolean

equalArea(E object1, E object2) {

return object1.getArea() == object2.getArea();

}

Page 19: Chapter 21 Generics

C++

•C++ templates are like Java generics.

•C++ creates multiple copies of code for different possible template instantiations.

•Java uses a single, general copy of code

19

Page 20: Chapter 21 Generics

Erasure

Java uses type erasure to create one version of code with a raw type.

•Type variables are erased and replaced by their bounding types

•What if no bounding types? Object•Cast - method calls that return raw type.

20

Page 21: Chapter 21 Generics

Raw Type and Backward Compatibility

// raw typeArrayList list = new ArrayList();

21

This is roughly equivalent to ArrayList<Object> list = new ArrayList<Object>();

Page 22: Chapter 21 Generics

Raw Type is Unsafe

Max.max("Welcome", 23);

22

// Max.java: Find a maximum object

public class Max {

/** Return the maximum between two objects */

public static Comparable max(Comparable o1, Comparable o2) {

if (o1.compareTo(o2) > 0)

return o1;

else

return o2;

}

}

Runtime Error:

Page 23: Chapter 21 Generics

Make it Safe

Max.max("Welcome", 23);

23

// Max1.java: Find a maximum object

public class Max1 {

/** Return the maximum between two objects */

public static <E extends Comparable<E>> E max(E o1, E o2) {

if (o1.compareTo(o2) > 0)

return o1;

else

return o2;

}

}

Compile-time Error:

Page 24: Chapter 21 Generics

Limitations•Primitive types cannot be used for type

parameter - use wrapper classes.

•Type inquiries (instanceof) yield only the raw types.

•Arrays cannot be of generic types. (Use ArrayList to collect generic types.)

24

Page 25: Chapter 21 Generics

Limitations (cont.)

•Cannot instantiate generic types. Error: new E().

•Type variables cannot be used in a static context - which type should they be?!

25

Page 26: Chapter 21 Generics

Inheritance

•No relationship between Pair<S> and Pair<T>, no matter how S and T are related

Why not? •Code won’t always work•(You can insert Double to ArrayList of

Number, not to ArrayList of Integer)

26

Page 27: Chapter 21 Generics

Wildcards

Why wildcards are necessary? See this example.

27

WildCardDemo1WildCardDemo1

? unbounded wildcard

? extends T bounded wildcard

? super T lower bound wildcard

WildCardDemo2WildCardDemo2 WildCardDemo3WildCardDemo3

Page 28: Chapter 21 Generics

Wildcards

? unbounded wildcard

? extends T bounded wildcard T or any of its subclasses

? super T lower bound wildcard T or any of its

superclasses

28

Page 29: Chapter 21 Generics

Generic Types and Wildcard Types

29

Object

?

? super E

E’s superclass

E

? extends E

E’s subclass

Object

A<?>

A<? super B>

A<B’s subclass>

A<? extends B>

A<B>

A<B’s superclass>

Page 30: Chapter 21 Generics

Wildcards

Advantage:•Wildcards provide flexibility when passing

parameterized types to a method.

Disadvantage:•Cannot be used as type name throughout

method body.

30

Page 31: Chapter 21 Generics

Avoiding Unsafe Raw Types Use

new ArrayList<ConcreteType>()

Instead of

new ArrayList();

31

TestArrayListNewTestArrayListNew RunRun

Page 32: Chapter 21 Generics

Erasure and Restrictions on Generics

Implementation of generics: type erasure.

The compiler uses the generic type information to compile the code, but erases it afterwards.

Generic information is not available at run time.

Backward-compatibility with legacy code that uses raw types.

32

Page 33: Chapter 21 Generics

Compile Time Checking

For example, the compiler checks whether generics is used correctly for the following code in (a) and translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.

33

ArrayList<String> list = new ArrayList<String>();

list.add("Oklahoma");

String state = list.get(0);

(a) (b)

ArrayList list = new ArrayList();

list.add("Oklahoma");

String state = (String)(list.get(0));

Page 34: Chapter 21 Generics

Important Facts

It is important to note that a generic class is shared by all its instances regardless of its actual generic type.

GenericStack<String> stack1 = new GenericStack<String>();

GenericStack<Integer> stack2 = new GenericStack<Integer>();

Although GenericStack<String> and GenericStack<Integer> are two types, there is only one class GenericStack loaded into the JVM.

34

Page 35: Chapter 21 Generics

Designing Generic Matrix Classes

•Objective: This example gives a generic class for matrix arithmetic. This class implements matrix addition and multiplication common for all types of matrices.

35

GenericMatrixGenericMatrix

Page 36: Chapter 21 Generics

UML Diagram

36

GenericMatrix<E>

#add(element1:E, element2: E): E #multiply(element1: E, element2: E): E #zero(): E +addMatrix(matrix1: E[][], matrix2: E[][]): E[][] +multiplyMatrix(matrix1: E[][], matrix2: E[][]): E[][] +printResult(m1: Number[][], m2: Number[][], m3: Number[][], op: char): void

IntegerMatrix

RationalMatrix