Finding the largest object ) Write a method that returns the largest object in a
ID: 3550091 • Letter: F
Question
Finding the largest object) Write a method that returns the largest object in an array of objects. The method signature is:
public static Object max(Comparable[] a)
All the objects are instances of the Comparable interface. The order of the objects in the array is determined using the compareTo method.
Write a test program that creates an array of ten strings, an array of ten integers, and an array of ten dates, and finds the largest string, integer, and date in the arrays.
Explanation / Answer
import java.util.Date; public class maxobject { public static int findMax(int[] nums) { int curMax = nums[0]; for (int i=1; i curMax) { curMax = nums[i]; } } return curMax; } public static String findMax(String[] strs) { String curMax = strs[0]; for (int i=1; i curMax.length()) { curMax = strs[i]; } } return curMax; } public static Date findMax(Date[] date) { Date curMax = new Date(); curMax = date[0]; for(int i=1;i0) { curMax=date[i]; } else if(date[i].compareTo(curMax)>0) { curMax = date[i]; } } return curMax; } public static void main(String args[]) { int[] nums = {1,2,3,4,5,6,7,8,9,10}; System.out.println("The max interger is: " +maxobject.findMax(nums)); String[] strs = {"apple","pear","orange","ten","a","is","building","program","baseball","cowboy"}; System.out.println("The max string is: " +maxobject.findMax(strs)); } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.