You are here: Home / Topics / Program to explain Generic Interfaces in Java

Program to explain Generic Interfaces in Java

Filed under: Java on 2024-04-13 09:09:43

//  Program to explain Generic Interfaces.

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

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;
}
}

public class GenericTest15j  
{
public static void main(String args[ ]) 
{
 Integer inums[ ] = { 3, 6, 2, 8, 6 };
 Character chs[ ] = { 'A', 'r', 'V', '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());
}
}

 

Output:

Max value in inums: 8
Min value in inums: 2
Max value in chs: V
Min value in chs: A

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.