Generic classes in Java
For my case I need a generic type for a private object created in the constructor of the class.
public class Matrix <T>{
private T [][] dataMatrix;
public Matrix (int nNew, int mNew){
dataMatrix = (T[][]) new Object[n][m];
}
}
If I need to use the same Generic Class in some variable definition in other method I will use the same tricky of casting an instance of Object. For exemple:
public void addRow (int pos, T value){
T [][] newMatrix = (T[][]) new Object[n+1][m];
n++;
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if (i<pos) newMatrix[i][j]=getMij(i,j);
if (i==pos) newMatrix[i][j]=value;
if (i>pos) newMatrix[i][j]=getMij(i-1,j);
}
}
dataMatrix = newMatrix;
}
From the wikipedia:
Generic class definitions
Here is an example of a generic class:
public class Pair<T, S> { public Pair(T f, S s) { first = f; second = s; } public T getFirst() { return first; } public S getSecond() { return second; } public String toString() { return "(" + first.toString() + ", " + second.toString() + ")"; } private T first; private S second; }
This generic class can be used in the following way:
Pair<String, String> grade440 = new Pair<String, String>("mike", "A"); Pair<String, Integer> marks440 = new Pair<String, Integer>("mike", 100); System.out.println("grade:" + grade440.toString()); System.out.println("marks:" + marks440.toString());
Generic method definitions
Here is an example of a generic method using the generic class above:
public <T> Pair<T,T> twice(T value) { return new Pair<T,T>(value,value); }
In many cases the user of the method need not indicate the type parameters, as they can be inferred:
Pair<String, String> pair = twice("Hello");
The parameters can be explicitly added if needed:
Pair<String, String> pair = this.<String>twice("Hello");
Generics in throws clause
Although exceptions themselves cannot be generic, generic parameters can appear in a throws clause:
public <T extends Throwable> void throwMeConditional (boolean conditional, T exception) throws T { if(conditional) throw exception; }