// GenericApplier.java is a generalization of applier2.java // with generic types. // UnaryFun is a generic interface declaring f as a function taking // an input of type T and returning a value of type S. interface UnaryFun { public S f(T x); } // Incr instantiates method f to be the increment function on Integers class Incr implements UnaryFun { public Integer f(Integer i) { return new Integer(i+1); } } // end Incr // IntSqrt instantiates method f to be the square root class IntSqrt implements UnaryFun { public Float f(Integer i) { return new Float(Math.sqrt(i)); } } // end IntSqrt class Applier { // Generic class // ApplyToArray applies Q.f to the elements of A and puts the result in B. public void ApplyToArray(UnaryFun Q, T[] A, S[] B) { for (int i = 0; i < A.length; i++) B[i] = Q.f(A[i]); } } // end Applier public class GenericApplier { public static void main(String args[]) { Integer A[] = new Integer[] { 1,2,3 }; Integer B[] = new Integer[3]; Float C[] = new Float[3]; Incr Inc = new Incr(); IntSqrt ISQ = new IntSqrt(); Applier IIApp = new Applier(); Applier IFApp = new Applier(); IIApp.ApplyToArray(Inc,A,B); System.out.println(B[0] + " " + B[1] + " " + B[2]); IFApp.ApplyToArray(ISQ,A,C); System.out.println(C[0] + " " + C[1] + " " + C[2]); } } // end GenericApplier