Java Generics - An Exploration
Outline
This article explores Java Generics by working through a simple problem that involves Java interfaces.
Pre-requisites
Basic knowledge of Java is assumed. For those new to the language, do consult and learn from other resources available, e.g. Java Tutorial for Beginners.
Reference
Java How to Program, 11/e, Early Objects Chapter 20
Introducing Generics
Available since Java SE 5.0 in 2004, Java Generics allow definitions of methods and classes that include parameters for type, commonly represented by T as in the following example. This can significantly reduce the amount of code that needs to be written for functionality that only differs in the data types are involved.
Example
Note
- generics only work with Java reference types
Problem for Exploration
The following is the problem we will be walking through for the rest of this article:
-
Part 1: Write java interface "Orderer" with method isLOE(). LOE stands for "is less than or equal to". The method takes two objects. It returns boolean value of true if the first object should be ordered before, or equal to the second.
-
Part 2: Write java class with a static method "minOf()" which takes in an ArrayList and an Orderer. It should return the least Object in the collection according to the Orderer in Part 1.
-
Part 3: Write test program that uses minOf() to find the alphabetically first in a list of Strings, Integers and Doubles.
Part 1
Notes on Part 1
- The type-parameter section specifies that T extends Comparable
, i.e. only objects of classes that implement interface Comparable can be used with this method. - Comparable
is known as the type parameter’s upper bound. By default, Object is the upper bound, meaning that an object of any type can be used. - Type-parameter declarations that bound the parameter always use keyword extends regardless of whether the type parameter extends a class or implements an interface.
- A class that implements Comparable
must implement compareTo() such that it compares the contents of two objects of that class and returns the comparison results. - Interface Comparable
’s documentation explains that compareTo() must return 0 if the objects are equal, a negative integer if object1 is less than object2 or a positive integer if object1 is greater than object2.
Part 2
Part 3
continuation of preceding screenshot:
- End Of Article -