0

Below is the class. The static method findMax returns arr[maxIndex] and when I try to print that out in the main method I get a memory location instead of the value. I thought to print out a value at a certain index of an array.

I would like to print the value, but without changing the existing method (so I have to fix the problem via the main).

public class Problem1 
 {
     public static <AnyType extends Comparable<AnyType>> AnyType findMax(AnyType[] arr) 
    {
        int maxIndex = 0;
        for (int i = 1; i < arr.length; i++)
            if ( arr[i].compareTo(arr[maxIndex]) > 0 )
               maxIndex = i;
        return arr[maxIndex];
    }

    public static void main(String[ ] args)
    {
        Rectangle rect1 = new Rectangle(1,2);
        Rectangle rect2 = new Rectangle(2,2);
        Rectangle rect3 = new Rectangle(3,2);
        Rectangle rect4 = new Rectangle(4,2);
        Rectangle rect5 = new Rectangle(5,3);

        Rectangle[ ] rectangles = new Rectangle[5];
        rectangles[0] = rect1;
        rectangles[1] = rect2;
        rectangles[2] = rect3;
        rectangles[3] = rect4;
        rectangles[4] = rect5;

        System.out.println(findMax(rectangles));

    }

}
Rao
  • 20,781
  • 11
  • 57
  • 77
l.a
  • 11
  • 1

2 Answers2

2

Your findMax() method returns a Rectangle. By default, Java does not know how to print a Rectangle. So you need to override toString() on that class. Currently, the default, Object.toString() is being used, which simply prints the hashcode.

dave
  • 11,641
  • 5
  • 47
  • 65
0

Override toString method of Rectangle class

abdulrafique
  • 304
  • 1
  • 11