Close
Register
Close Window

Masters of Engineering Bridge Course

Chapter 10 Queues and Generics

Show Source |    | About   «  9.2. Software Design and MVC   ::   Contents   ::   10.2. Queues  »

10.1. Generics 2

10.1.1. Objectives

Upon completion of this module, students will be able to:

  • Determine when a generic needs to be bounded

  • Write and use methods and classes that use bounded generic parameters

  • Write and use bounded generic methods

  • Become familiar with syntax for wildcards

10.1.2. Generics 2

10.1.2.1. [10:53] Generics 2 Video

TODO: fix URLS.

Generics2.pptx

10.1.2.2. [17:26] Reflecting on Generics Video

10.1.2.3. Code

TODO: fix URLS.

CS2-ExGenerics2.zip

10.1.2.5. Checkpoint 1

10.1.3. Sample Declarations of Generic Methods Explained

The format for declaring a Generic method is as follows:

methodModifiers <genericParameters> returnType methodName(methodParameters)

Note the use of the generic parameters placed inside the angle brackets.

Example 1

Below is one example of how you may declare a Generic method.

public static <T> void sort(T[] items, Comparator<? super T> comp)

The T following the static keyword and enclosed within the angle brackets represents the generic parameter for the sort method. The T should also appear in the method parameter list.

The second method parameter Comparator<? super T> comp is our way of specifying that comp must be an object that implements the Comparator interface for type T or for a superclass of type T

We use this approach to specify restrictions, for example, you can define a class that implements Comparator<Number> and use it to sort an array of Integer objects or an array of Double objects

Example 2

Below is another example Generic method declaration.

public static <T extends Comparable<T>> void sort(List<T> list)

The use of <T extends Comparable<T>> specifies that the generic parameter T must implement the interface Comparable<T>. The method parameter list (the object being sorted) is of type List<T>.

10.1.4. Bounded Wildcard Examples

10.1.4.1. [10:43] Bounded Wildcards Example Video

10.1.4.2. Code

TODO: fix URLS.

CS2-ExGenerics2.zip

10.1.5. Programming Practice: Generics 1

   «  9.2. Software Design and MVC   ::   Contents   ::   10.2. Queues  »

nsf
Close Window