chapter 21 generics

16
1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pears on Education, Inc. All rights reserved. 0-13-222158-6 Chapter 21 Generics Chapter20 Lists,Stacks,Q ueues, Trees, and H eaps Chapter21 G enerics Chapter22 Java C ollectionsFram ew ork Chapter23 A lgorithm Efficiency and Sorting Chapter11 O bject-O riented D esign Chapter19 R ecursion

Upload: rooney-franklin

Post on 31-Dec-2015

33 views

Category:

Documents


0 download

DESCRIPTION

Chapter 21 Generics. Objectives. To use generic classes and interfaces (§21.2). To declare generic classes and interfaces (§21.3). To understand why generic types can improve reliability and robustness (§21.3). To declare and use generic methods and bounded generic types (§21.4). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 21 Generics

1Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Chapter 21 Generics

Chapter 20 Lists, Stacks, Queues, Trees, and Heaps

Chapter 21 Generics

Chapter 22 Java Collections Framework

Chapter 23 Algorithm Efficiency and Sorting

Chapter 11 Object-Oriented Design

Chapter 19 Recursion

Page 2: Chapter 21 Generics

2Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Objectives To use generic classes and interfaces (§21.2). To declare generic classes and interfaces (§21.3). To understand why generic types can improve reliability

and robustness (§21.3). To declare and use generic methods and bounded generic

types (§21.4). To use raw types for backward compatibility (§21.5). To know wildcard types and understand why they are

necessary (§21.6). To understand that all instances of a generic class share the

same runtime class file (§21.7). To convert legacy code using JDK 1.5 generics (§21.8). To design and implement a generic matrix class (§21.9).

Page 3: Chapter 21 Generics

3Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

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 compile warning on this line, you need to learn JDK 1.5 generics.

Page 4: Chapter 21 Generics

4Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Generic Type

package java.lang; public interface Comaprable { 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 5: Chapter 21 Generics

5Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Generic ArrayList in JDK 1.5 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 6: Chapter 21 Generics

6Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

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

}

}No compile warning on this line.

Page 7: Chapter 21 Generics

7Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

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

Page 8: Chapter 21 Generics

8Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Declaring Generic Classes and Interfaces GenericStack<E>

-elements: E[]

-size: int

+GenericStack()

+GenericStack(initialCapacity: int)

+getSize(): int

+peek(): E

+pop(): E

+push(o: E): E

+isEmpty(): boolean

Creates an empty stack with default initial capacity 16.

Creates an empty stack with the specified initial capacity.

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.

Return true if the stack is empty.

An array to store elements.

The number of the elements in this stack.

GenericStackGenericStack

Page 9: Chapter 21 Generics

9Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Generic Methods 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 10: Chapter 21 Generics

10Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Bounded Generic Type

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.findArea() == object2.findArea();

}

Page 11: Chapter 21 Generics

11Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Raw Type and Backward Compatibility

// raw typeGenericStack stack = new GenericStack();

This is roughly equivalent to GenericStack<Object> stack = new GenericStack<Object>();

Page 12: Chapter 21 Generics

12Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Raw Type is Unsafe

Max.max("Welcome", 23);

// 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 13: Chapter 21 Generics

13Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Make it Safe

Max.max("Welcome", 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;

}

}

Page 14: Chapter 21 Generics

14Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Wildcards

WildCardDemo1WildCardDemo1

Why wildcards are necessary? See this example.

? unbounded wildcard

? Extends T bounded wildcard

? Super T lower bound wildcard:

WildCardDemo2WildCardDemo2 WildCardDemo3WildCardDemo3

Page 15: Chapter 21 Generics

15Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

Generic Types and Wildcard Types

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 16: Chapter 21 Generics

16Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

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, but there is only one class GenericStack loaded into the JVM.