lecture02 java generics

28
Ad d J Ad d J i Advanced Java Advanced Java Programming Programming Lecture Lecture-02 02-Java Generics Java Generics Aatif Aatif Kamal Kamal, Dept. of Computing , Dept. of Computing [email protected] [email protected]

Upload: mustafasaeed3

Post on 29-Dec-2014

162 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lecture02 Java Generics

Ad d J Ad d J iiAdvanced Java Advanced Java ProgrammingProgrammingLectureLecture--0202--Java GenericsJava Generics

AatifAatif KamalKamal, Dept. of Computing, Dept. of [email protected]@seecs.edu.pk

Page 2: Lecture02 Java Generics

Objectives

To know the benefits of genericsTo use generic classes and interfaces

Object es

To use generic classes and interfacesTo declare generic classes and interfacesTo understand why generic types can improve reliability and readabilityreadabilityTo declare and use generic methods and bounded generic typesTo use raw types for backward compatibilityTo know wildcard types and understand why they are necessaryTo know wildcard types and understand why they are necessaryTo convert legacy code using JDK 1.5 genericsTo understand that generic type information is erased by the compiler and all instances of a generic class share the same runtime p gclass fileTo know certain restrictions on generic types caused by type erasureTo design and implement generic matrix classes

2

Page 3: Lecture02 Java Generics

Java GenericsJava GenericsWhen you take an element out of a Collection, you must castmust cast it to the type of element that is stored inmust cast must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast i h h ll i ' his the same as the collection's type, so the cast can fail at run time. Generics provides a way for you to communicate theGenerics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type p ypof the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of thethe correct casts on values being taken out of the collection.

Page 4: Lecture02 Java Generics

Java Generics Intro

You may be familiar with similar constructs fromYou may be familiar with similar constructs from other languages, most notably C++ templates. there are both similarities and important differencesGenerics allow you to abstract over types

List myIntList = new LinkedList(); // 1y ()myIntList.add(new Integer(0)); // 2Integer x = (Integer) myIntList.iterator().next(); // 3

Page 5: Lecture02 Java Generics

Why do you Get a warning

public class ShowUncheckedWarning {

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");}}

}

To understand the compileTo understand the compile warning on this line, you need to learn JDK 1.5 generics.

5

learn JDK 1.5 generics.

Page 6: Lecture02 Java Generics

Java Generics IntroJa a Ge e cs t o

List myIntList = new LinkedList(); // 1myIntList.add(new Integer(0)); // 2Integer x = (Integer) myIntList.iterator().next(); // 3g ( g ) y () (); //

List<Integer> myIntList = new LinkedList<Integer>(); // 1’myIntList add(new Integer(0)); //2’myIntList.add(new Integer(0)); //2’Integer x = myIntList.iterator().next(); // 3’

Page 7: Lecture02 Java Generics

Fix the Warning

public class ShowUncheckedWarning {

t e a g

public class ShowUncheckedWarning {

public static void main(String[] args) {

java.util.ArrayList<String> list =

new java.util.ArrayList<String>();

list.add("Java Programming");

`

}

}

No compile warning on this line.

7

Page 8: Lecture02 Java Generics

What is Generics?

Generics is the capability to parameterize types. 

at s Ge e cs

Generics is the capability to parameteri e types.With this capability, you can define a class or a method with generic types that can be substituted 

b h lusing concrete types by the compiler. For example, you may define a generic stack class that stores the elements of a generic type Fromthat stores the elements of a generic type. From this generic class, you may create a stack object for holding strings and a stack object for holding g g j gnumbers. Here, strings and numbers are concrete types that replace the generic type.

8

Page 9: Lecture02 Java Generics

Why Generics?

The key benefit of generics is to enable errors to be

y Ge e cs

The key benefit of generics is to enable errors to be detected at compile time rather than at runtime. A generic class or method permits you to specifyA generic class or method permits you to specify allowable types of objects that the class or method may work with.may work with. If you attempt to use the class or method with an incompatible object the compile error occursincompatible object, the compile error occurs.

9

Page 10: Lecture02 Java Generics

Generic Type

package java.lang; package java.lang;

Ge e c ype

public interface Comaprable { public int compareTo(Object o)

}

public interface Comaprable<T> { public int compareTo(T o)

}

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

Generic InstantiationGeneric InstantiationRuntime error

Comparable c = new Date(); Comparable<Date> c = new Date();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

10

Compile errorImproves reliability

Page 11: Lecture02 Java Generics

Generic ArrayList in JDK 1.5 java.util.ArrayList

+ArrayList()

java.util.ArrayList<E>

+ArrayList()

Ge e c ay st J 5

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

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

+contains(o: Object): boolean +get(index: int) : Object +indexOf(o: Object) : int

+clear(): void+contains(o: Object): boolean +get(index: int) : E +indexOf(o: Object) : int+indexOf(o: Object) : int

+isEmpty(): boolean +lastIndexOf(o: Object) : int +remove(o: Object): boolean

+indexOf(o: Object) : int+isEmpty(): boolean +lastIndexOf(o: Object) : int +remove(o: Object): booleanremove(o: Object): boolean

+size(): int +remove(index: int) : boolean +set(index: int, o: Object) : Object

remove(o: Object): boolean+size(): int +remove(index: int) : boolean +set(index: int, o: E) : E

11

( , j ) j ( , )

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

Page 12: Lecture02 Java Generics

No Casting Needed

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

No Casting Needed

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

12

Page 13: Lecture02 Java Generics

Declaring Generic Classes and Interfaces

GenericStack<E>

Declaring Generic Classes and Interfaces

-list: java.util.ArrayList<E>

+GenericStack() Creates an empty stack.

An array list to store elements.

+getSize(): int +peek(): E +pop(): E

Returns the number of elements in this stack. Returns the top element in this stack. Returns and removes the top element in this stack.p p()

+push(o: E): E +isEmpty(): boolean

pAdds a new element to the top of this stack. Returns true if the stack is empty.

G i S k

13

GenericStack

Page 14: Lecture02 Java Generics

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

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

Ge e c et ods

for (int i   0; i < list.length; i ) System.out.print(list[i] + " ");

System.out.println();}}

public static void print(Object[] list) {public static void print(Object[] list) {for (int i = 0; i < list.length; i++) 

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

}

14

Page 15: Lecture02 Java Generics

Bounded Generic Type

public static void main(String[] args ) {

ou ded Ge e c ype

p ( g[] g ) {Rectangle rectangle = new Rectangle(2, 2);Circle9 circle = new Circle9(2);System out println("Same area? " + equalArea(rectangle circle));System.out.println( Same area?   + equalArea(rectangle, circle));

}

bli t ti E t d G t i Obj t b lpublic static <E extends GeometricObject> boolean     equalArea(E object1, E object2) {

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

15

Page 16: Lecture02 Java Generics

Raw Type and backward Compatibility

// raw type

Raw Type and backward Compatibility 

// raw typeArrayList list = new ArrayList();

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

16

Page 17: Lecture02 Java Generics

Raw Type is Unsafe// Max.java: Find a maximum objectpublic class Max {

a ype s U sa e

public class Max {/** Return the maximum between two objects */public static Comparable max(Comparable o1, 

C bl 2) {Comparable o2) {   if (o1.compareTo(o2) > 0)

return o1;else

return o2;}}

}Runtime Error: 

Max.max("Welcome", 23); 17

Page 18: Lecture02 Java Generics

Make it Safe// Max1.java: Find a maximum objectpublic class Max1 {

a e t Sa e

public class Max1 {/** Return the maximum between two objects */public static <E extends Comparable<E>> E p pmax(E o1, E o2) {   if (o1.compareTo(o2) > 0)

return o1;else

return o2;return o2;}

}Max.max("Welcome", 23);

18

}

Page 19: Lecture02 Java Generics

Wildcards

Why wildcards are necessary? See this example.

Wildcards

WildCardDemo1WildCardDemo1

?                              unbounded wildcard ? t d T b d d ild d? extends T             bounded wildcard ? super T                 lower bound wildcard 

WildCardDemo2WildCardDemo2 WildCardDemo3WildCardDemo3

19

Page 20: Lecture02 Java Generics

Generic Type and Wildcard Types

j

Ge e c ype a d dca d ypes

Object

? ? super E E’s superclass

Object

A<?>

E A<? super B>A<? extends B>

? extends E E’s subclass A<B’s subclass> A<B> A<B’s superclass>

20

Page 21: Lecture02 Java Generics

Avoiding Unsafe Raw Types

Use 

o d g U sa e a ypes

new ArrayList<ConcreteType>()

Instead of 

new ArrayList();TestArrayListNewTestArrayListNew RunRun

21

Page 22: Lecture02 Java Generics

Ensure and Restrictions on Generics

Generics are implemented using an approach called 

Ensure and Restrictions on Generics

type erasure. The compiler uses the generic type information to compile the code, but erases it ft d S th i i f ti i t il blafterwards. So the generic information is not available at run time. This approach enables the generic code to be backward compatible with the legacy code thatbe backward‐compatible with the legacy code that uses raw types.

22

Page 23: Lecture02 Java Generics

Compile Time Checking

For example, the compiler checks whether generics is 

Compile Time Checking

p , p gused 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.

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

list.add("Oklahoma");

String state = list.get(0);

ArrayList list = new ArrayList();

list.add("Oklahoma");

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

(a) (b)

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

23

Page 24: Lecture02 Java Generics

Important Facts

It is important to note that a generic class is h d b ll it i t dl f it t l

po ta t acts

shared by all its instances regardless of its actual generic type. 

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

GenericStack<Integer>();GenericStack<Integer>();

Although GenericStack<String> and GenericStack<Integer>b h i l l G i S kare two types, but there is only one class GenericStack

loaded into the JVM. 

24

Page 25: Lecture02 Java Generics

Retractions on Generics

Restriction 1: Cannot Create an Instance of a Generic Type (i e new E())

et act o s o Ge e cs

Type. (i.e., new E()).

Restriction 2: Generic Array Creation is Not AllowedRestriction 2: Generic Array Creation is Not Allowed. (i.e., new E[100]).

Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context.

Restriction 4: Exception Classes Cannot be Generic.

25

Page 26: Lecture02 Java Generics

Designing Generic Matrix ClassesObjective: This example gives a generic class for matrix arithmetic This class implements matrix

es g g Ge e c at C asses

matrix arithmetic. This class implements matrix addition and multiplication common for all types of matrices.of matrices.

GenericMatrixGenericMatrix

26

Page 27: Lecture02 Java Generics

UML Diagram

U ag a

GenericMatrix<E> #add(element1:E, element2: E): E #multiply(element1: E, element2: E): E

IntegerMatrix

#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[][], printResult(m1: Number[][], m2: Number[][],

m3: Number[][], op: char): void RationalMatrix

27

Page 28: Lecture02 Java Generics

Generic Type

Objective: This example gives two programs that 

yp

utilize the GenericMatrix class for integer matrix arithmetic and rational matrix arithmetic.

TestIntegerMatrixTestIntegerMatrix RunRunIntegerMatrixIntegerMatrix

TestRationalMatrixTestRationalMatrix RunRunRationalMatrixRationalMatrix

28