A generics working example: how to embed two classesFrom WikiJavabuy this book
This is a full working example.
the articleThe following class Pair has 2 type parameters, E and F, and its instances are pair of objects where we have defined the obvious projections. Look out the type variables in the body of the class. This class could be useful in the quite common situation where a method has to return 2 values. Be careful that the filename .java and the constructor of the generic class are just Pair and NOT Pair<E,F>. Note also that when you declare more than one formal parameter these are bounded between a single couple of angular parenthesis and separated by commas. Pair.javapublic class Pair<E,F> { // internal rappresentation private E first; private F second; // constructor public Pair(E first, F second){ this.first = first; this.second = second; } public E getFirst() { return first; } public F getSecond() { return second; } // toString - overridden from Object public String toString(){ return "("+ first + "," + second + ")"; } }
|
