Starting with 5.0, Java includes a generic framework for using abstract types in a way that avoids many explicit casts. A generic type is a type that is not defined at compilation time, but becomes fully specified at run time.
public class Pair<K,V>{
K key;
V value;
public void set(K k, V v){
key = k;
value = v;
}
public K getKey(){return key;}
...
public String toString(){
return getKey() + "," + getValue()'
}
public static void main(String[] args){
Pair<String,Integer> p1 = new Pair<String,Integer>();
p1.set(new String("S",new Integer(36));
..
}
The actual type parameter can be an arbitrary type. To restrict the type of an actual parameter, we can use an extends clause. e.g. public class PersonPair<P extends Person>
public class Pair<K,V>{
K key;
V value;
public void set(K k, V v){
key = k;
value = v;
}
public K getKey(){return key;}
...
public String toString(){
return getKey() + "," + getValue()'
}
public static void main(String[] args){
Pair<String,Integer> p1 = new Pair<String,Integer>();
p1.set(new String("S",new Integer(36));
..
Pair<User,Double> p2 = new Pair<User,Double>();
p1.set(new User("xu"),new doubule(36));
}
The actual type parameter can be an arbitrary type. To restrict the type of an actual parameter, we can use an extends clause. e.g. public class PersonPair<P extends Person>
Comments
Post a Comment