Write a method that returns the largest object in an array of objects.

0 Nova Dadow · April 3, 2015

Write a method that returns the largest object in an array of objects. The method signature is:

public static Object max(java.lang.Comparable[] a)

All the objects are instances of the java.lang.Comparable interface. The order of the objects in the array is determined using the compareTo method.

Write a test program in the main method that creates an array of ten Strings, an array of ten Integers, and an array of ten java.util.Dates, and finds the largest string (i.e. in the alphabetical order), Integer, and Date in the arrays.

Name your java class Max and your java file Max.java.
I am having a hard time grasping what exactly I need to do in this assignment. So any clarification would be greatly appreciated. The two things I am really struggling with is how to use an interface and the compareTo method. To my understanding interfaces only hold methods then I would have to call the compareTo method outside of the interface?? Anyway this is what I have so far. I would appreciate some opinions on the code and if I am on the right track with this code at all or simply help clarifying the directions.

public class Max {

    public static Object max(java.lang.Comparable[] a) {

        Object tempObj = new Object();

        for (int i = 0; i < a.length - 1; i++) {
            if ((a[i]).compareTo(a[i + 1]) > 0)
                tempObj = a[i];
                tempObj = a[i + 1];

        return tempObj;

    // compare toMethod
    public void CompareTo() {
        a[i].compareTo(a[i + 1]);
}// End Main

class MaxTest implements Max {
    public void main(String[] args) {

        Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        String[] stringArray = { "a", "b", "c", "d", "e", "f", "g", "h", "i",
                "j" };
        java.util.Date[] dateArray = {};

        for (int j = 0; j < 10; j++)
            dateArray[j] = new java.util.Date();

    }// End Main
}//End Class

Post a Reply


Oldest  Newest  Rating
0 vikram patange · April 5, 2015
yu can reffers this

public class Animal implements Comparable {
      public String name;
      public int year_discovered;
      public String population;

public Animal(String name, int year_discovered, String population){
      this.name = name;
      this.year_discovered = year_discovered;
      this.population = population; }

public String toString(){
   String s = "Animal name: "+ name+"\nYear Discovered: +year_discovered+"\nPopulation: "+population;
   return s;

   public int compareTo(Object o) {
       Animal a = (Animal) o;
       return this.year_discovered - o.year_discovered;
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator