In: Computer Science
Write out a generic java code to find a largest element from n comparable objects (default) and use a main method to test.
All the explanation is provided in the comments of the code itself.
CODE--
public class CompareGeneric
{
public static Comparable find_Largest(Comparable
arr[])
{
//declare and initialize a variable
to store the largest value
Comparable largest=arr[0];
//iterate over the array and find
the largest
for(int
i=1;i<arr.length;i++)
{
if(arr[i].compareTo(largest)>0)
{
largest=arr[i];
}
}
//finally return largest
return largest;
}
public static void main(String[] args)
{
Double[] d= {2.0,5.7,22.4};
System.out.println("Largest Double:
"+find_Largest(d));
Integer[] i=
{1,2,3,4,5,6,7,8,9};
System.out.println("Largest
Integer: "+find_Largest(i));
}
}
OUTPUT SCREENSHOT--
NOTE--
Please upvote if you like the effort.