Generics allow you to create a type-safe way of storing a 'generic' class type ( and thanks to autoboxing primitive types aswell ).
On methods, you can define template parameters in the following way:
< Template_Paramter, TemplateParam2 > returnType methodName( arguments ... ) {
}
The template parameters can now be used anywhere in that method ( including the arguments and return type ) as normal class type 'types'.
To see an application of this, consider the following method that returns the third element of (almost) any array type:
void main(){
String[] s = { "hi", "how", "are", "you" };
String third = getElement3( s );
println( third );
}
< T > T getElement3( T[] array ){
return array[2];
}
I say almost any array type because this won't work on arrays of primitive types, but if you create an array of Integer (or the other class-type equivalent) then you can get the same effect:
void main(){
Integer[] ints = { 1,2,3,4,5};
int third = getElement3( ints );
println( third );
}
< T > T getElement3( T[] array ){
return array[2];
}
Template parameters can also be used in classes, below is a class which stores a pair of Type-Parameterd objects:
class Pair<T>{
T a;
T b;
}
To create an instance of this class, we must say what the type-parameters are bound to. Note, in Kenya if you use a primitive type as the binding type, it is internally automatically converted up to the class type for you; i.e.:
void main() {
Pair<String> twoStrings;
twoStrings.a = "hello";
twoStrings.b = "world";
//This is equivalent to Pair<Integer>
Pair<int> twoInts;
twoInts.a = 3;
twoInts.b = 4;
}
class Pair<T>{
T a;
T b;
}