Definition of a Simple Generic Class Core Java

A generic class is a class with one or more type variables. In this chapter, we use a simplePair class as an example. This class allows us to focus on generics without being distractedby data storage details. Here is the code for the generic Pair class:

The Pair class introduces a type variable T, enclosed in angle brackets <>, after the classname. A generic class can have more than one type variable. For example, we couldhave defined the Pair class with separate types for the first and second field:

The type variables are used throughout the class definition to specify method returntypes and the types of fields and local variables. For example:

You instantiate the generic type by substituting types for the type variables, such as

In other words, the generic class acts as a factory for ordinary classes. The program in Listing below puts the Pair class to work. The static minmax methodtraverses an array and simultaneously computes the minimum and maximum value. Ituses a Pair object to return both results. Recall that the compareTo method compares twostrings, returning 0 if the strings are identical, a negative integer if the first string comesbefore the second in dictionary order, and a positive integer otherwise.

PairTest1.java

C++ NOTE: Superficially, generic classes in Java are similar to template classes in C++.The only obvious difference is that Java has no special template keyword. However, asyou will see throughout this section, there are substantial differences between these twomechanisms.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics