Search code examples
javasortinggenericsmultidimensional-arraycomparable

Max element in a 2 dimensional array using generics


I have all my code completed and I can't for the life of me figure out why when I run this that the max element is 5 and not 6. Any help is gratefully accepted.

public class MaxElement2DimArray 
{
    public static void main(String[] args) 
    {
        Integer[][] numbers = { {1, 2, 3}, {4, 5, 6} };
        System.out.println("Max element in array is: " +max(numbers));
    }

    public static<E extends Comparable<E>> E max(E[] [] list) 
    {
        E max = list[0][0];
        for (int i=1; i<list.length; i++) 
        {
            for (int j=1; j<list.length; j++) 
            {
                if (max.compareTo(list[i][j]) < 0) 
                {
                    max = list[i][j];
                }
            }
        }
        return max;
    }
}

Solution

  • Your inner for loop only iterates twice since it references the outer list's length. It should reference the inner list's length

    for (int j=0; j<list[i].length; j++){
        ...
    }
    

    Also, you start your index at 1, so you will skip the entire first inner array, and the first element of every other array.