Before the advent of Java 5 we had only Arrays, Properties, and HashMap. But
with Java 5 and generics features, building a ValuePair has become
simpler. In fact generics is the concept that
generalizes the use of variables. The situation with generics is quite simple but building classes with them is a tuff task. The
syntax is complex and the abstraction level is high.
Java generics takes several
steps to use them:
first define an interface:
public interface Couple<P, Q> {
public P getIndex();
public Q getValue();
} |
The code is simple but slightly different if the developer is unknown with
the Java 5 syntax. The first thing that is new to the developer is the use of <P, Q>. These are nothing but the generic types that has to be defined
later. These types are not known in advance and is available at compile time (at the
time of declaration of these variables). To clearly understand lets see the
implementation:
public class ValuePair<A, B> implements Couple<A, B> {
private A a;
private B b;
public ValuePair(A a, B b) {
this.a = a;
this.b = b;
}
public A getIndex() {
return a;
}
public B getValue() {
return b;
}
} |
Now there should not have much more confusion about generics. Since the class
includes the generified interface therefore it also includes the generic types.
We can use these generic types of any two different types (such as int and
float, long and int or any combination of two different types.) Things are going
to be more interested while subclassing a base class.
public class NameValuePair<T> extends ValuePair<String, T> {
public NameValuePair(String a, T b) {
super(a, b);
}
public String getName() {
return getIndex();
}
} |
From the above code it is clearly understood that only one parameter is
required because other parameter is already defined as the String.
You have seen the advantages of using generic classes. We can use them as a
family of variables according their signature.
|