Java Reference
In-Depth Information
classes that encapsulate a pair of objects of arbitrary types. This would typically arise where one object is
used as a key to access another object that represents a value in a collection. For example, you might store
Person objects in a collection that encapsulates personal details such as the name, the address, and the phone
number. You could associate each Person object with a Name object that you use as a key to retrieve the
Person object. One way of establishing the association between an object and its key is to encapsulate both
in another object — of type Pair , say.
Here's how you might define a generic type, Pair<K,V> , to be used for defining classes that encapsulate
a key/value pair of any type:
public class Pair <KeyType, ValueType> {
// Constructor
public Pair(KeyType aKey, ValueType aValue) {
key = aKey;
value = aValue;
}
// Get the key for this pair
public getKey() {
return key;
}
// Get the value for this pair
public getValue() {
return value;
}
// Set the value for this pair
public setValue(ValueType aValue) {
value = aValue;
}
private KeyType key;
private ValueType value;
}
Obviously, a practical definition would be more complicated than this — you'd need a means of compar-
ing key objects, for example — but it suffices to show how you can use two parameters in the definition of
a generic type.
Here's an example of how you could use this generic type:
Pair<String, String> entry = new Pair<>("Fred Thrump", "212 222 3333");
This creates an object of type Pair<String, String> and stores a reference to it in entry . The element
type parameters in the constructor call are inferred from the type of the variable on the left of the assign-
ment, just as for generic types with a single type parameter.
Type Parameter Scope
The scope of a type parameter is the entire generic class definition, but excluding any static members or
initializers in the class. This implies that you cannot specify the type of a static field within a generic type
definition as any of the type parameters for the generic type. Similarly, static methods cannot have paramet-
Search WWH ::




Custom Search