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

    }

}
2
  • 4
    Presumably you need to Override toString in Rectangle. Commented Feb 5, 2016 at 3:58
  • 1
    Look into using Arrays.toString(). Commented Feb 5, 2016 at 3:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Override toString method of Rectangle class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.