More about Generics Java Interlude 3 Data Structures

More about Generics Java Interlude 3 Data Structures and Abstractions with Java, 4 e Frank Carrano © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Interface Comparable • Consider the method compare. To for class String • if s and t are strings, s. compare. To(t) is – Negative if s comes before t – Zero if s and t are equal – Positive if s comes after t © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Interface Comparable • By invoking compare. To, you compare two objects of the class T. • LISTING JI 3 -3 The interface java. lang. Comparable © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Interface Comparable • Create a class Circle, define compare. To © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Generic Methods Listing JI 3 -2 An example of a generic method © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Generic Methods Listing JI 3 -2 An example of a generic method © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bounded Type Parameters Consider this simple class of squares: © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bounded Type Parameters Note the different types of square objects possible. © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bounded Type Parameters Imagine that we want to write a static method that returns the smallest object in an array. Suppose that we wrote our method shown above © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bounded Type Parameters Header really should be as shown © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Wildcards • Question mark, ? , is used to represent an unknown class type § Referred to as a wildcard • Consider following method and objects © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Wildcards • Method display. Pair will accept as an argument a pair of objects whose data type is any one class © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bounded Wildcards FIGURE JI 3 -1 The class Gadget is derived from the class Widget, which implements the interface Comparable © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

End Java Interlude 3 © 2015 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.
- Slides: 14