Java – Generic Constructor Example

class GenericConstructor {
    private double value;

    <T extends Number> GenericConstructor(T arg) {
        value = arg.doubleValue();
    }

    void showValue() {
        System.out.println("value: " + value);
    }
}

public class GenericConstructorTest {

    public static void main(String args[]) {
        GenericConstructor gc1 = new GenericConstructor(100);
        GenericConstructor gc2 = new GenericConstructor(123.5F);

        gc1.showValue();
        gc2.showValue();
  }

}

Output:

value: 100.0
value: 123.5

Java – Generic Interface Example

MinMax.java

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

MyClass.java

class MyClass<T extends Comparable<T>> implements MinMax<T> {
  T[] vals; 

  MyClass(T[] o) { vals = o; } 

  public T min() {
    T v = vals[0];
    for(int i=1; i < vals.length; i++)
      if(vals[i].compareTo(v) < 0) v = vals[i]; 

    return v;
  } 

  public T max() {
    T v = vals[0]; 

    for(int i=1; i < vals.length; i++)
      if(vals[i].compareTo(v) > 0) v = vals[i]; 

    return v;
  }
}

GenIFDemo.java

public class GenIFDemo {
  public static void main(String args[]) {
    Integer inums[] = {3, 6, 2, 8, 6 };
    Character chs[] = {'b', 'r', 'p', 'w' }; 

    MyClass<Integer> iob = new MyClass<Integer>(inums);
    MyClass<Character> cob = new MyClass<Character>(chs); 

    System.out.println("Max value in inums: " + iob.max());
    System.out.println("Min value in inums: " + iob.min()); 

    System.out.println("Max value in chs: " + cob.max());
    System.out.println("Min value in chs: " + cob.min());
  }
}

Java – Generic Method Example

public class GenericMethodTest {
   // generic method printArray
   public static < E > void printArray( E[] inputArray ) {
         // Display array elements
         for ( E element : inputArray ) {
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] ) {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    }
}

Page 1 of 212