Generic Interfaces

We can also define generic interfaces.  Generic interfaces are specified just like generic classes.  The type parameter is specified after the name of the interface.

interface MinMaxInterface <T extends Comparable<T>> {
     T min();
     T max();
}

The type parameter of this interface is T.  Here T is bounded, requiring the type parameter be replaced with a class that extends the Comparable class.

An implementation of MinMaxInterface that includes an array of objects is below.  Notice that the type parameter of the class is the same as the type parameter of the interface and the implements clause states the name of the interface and the type parameter defined for the class (T).

public class MinMaxImp <T extends Comparable<T>> implements MinMaxInterface<T> {
     T[] elements;

     MinMaxImp(T[] arg) {
          elements = arg;
     }

     public T min() {
          if (elements.length == 0) {
              return null;
          }
          T min = elements[0];
          for (T next : elements) {
               if (next.compareTo(min) < 0) {
                     min = next;
               }
          }
          return min;
     }
 
     public T max() {
         if (elements.length == 0) {
             return null;
         }
         T min = elements[0];
         for (T next : elements) {
             if (next.compareTo(min)  > 0) {
                 min = next;
             }
         }
         return min;
     }
}

Below we see a driver that creates an array of integers and passes it to a MinMaxImp constructor.  The minimum and maximum values of the elements in the array are then printed to standard out.   We follow that by doing the same for an array of String.

public static void main(String[] args) {

     Integer[] arr = {3,1,4,2};

     MinMaxImp <Integer> mmi = new MinMaxImp <Integer> (arr);

     System.out.println("Min: " + mmi.min());
     System.out.println("Max: " + mmi.max());

     String[] arr2 = {"one", "two", "three", "four"};

     MinMaxImp <String> mmi2 = new MinMaxImp <String> (arr2);

     System.out.println("Min: " + mmi2.min());
     System.out.println("Max: " + mmi2.max());
}

© 2017 – 2019, Eric. All rights reserved.