Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0.
Generics allows parameterized type to use with method, class and interface.
This example code shows how to create and use Generic Interface in Java.
MinMax.java
1 2 3 4 |
interface MinMax<T extends Comparable<T>> { T min(); T max(); } |
MyClass.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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()); } } |