JI 03 More about Generics
Download
Report
Transcript JI 03 More about Generics
More about Generics
Java Interlude 3
Data Structures and Abstractions with Java, 4e
Frank Carrano
© 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Interface Comparable
• Consider the method compareTo for
class String
• if s and t are strings, s.compareTo(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 compareTo, you compare
two objects of the class T.
• LISTING JI3-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
compareTo
© 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Generic Methods
Listing JI3-2 An example of a generic method
© 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Generic Methods
Listing JI3-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 displayPair 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 JI3-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.