returns 二维数组的最大值 Java 的方法

Method that returns the maximum of a 2D-Array Java

public static <E extends Comparable<E>> E getMaxElement(E[][] list){
    E theMaximumElement = new E();
    for (int i = 0; i <list.length ; i++) {
        for (int j = 0; j <list[i].length ; j++) {

            if(theMaximumElement.compareTo(list[i][j]))
                theMaximumElement = list[i][j];
        }
    }
    return theMaximumElement;
}

我怎样才能写好这段代码?是真的吗?

我想求最大元素。我不擅长 java.

中的泛型

您的代码中有两个问题:

  • Comparable::compareTo 方法不是 return boolean,而是 int。下面是方法的描述:

    Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

  • 您不能实例化通用对象,例如new E()。检查 Instantiating generics type in java.

这是一条路:

public static <E extends Comparable<E>> E getMaxElement(E[][] list) {

    E theMaximumElement = list[0][0];                // initial value (the first one)
    for (final E[] array : list) {
        for (final E e : array) {
            if (theMaximumElement.compareTo(e) < 0)  // comparison is against 0
                theMaximumElement = e;               // setting the new maximum value
        }
    }
    return theMaximumElement;                        // returning it
}

唯一的条件是元素 list[0][0] 存在,即数组不为空。否则,您应该修改解决方案以使用 Optional<E>,因为并不总能找到最大值(空数组)。

从 Java 8 开始,有一种使用 :

来处理此类用例的简单方法
Optional<E> optionalmaximum = Arrays.stream(list)                    // Stream<E[]>
                                    .flatMap(Arrays::stream)         // Stream<E>
                                    .max(Comparator.naturalOrder()); // Optional<E>

这是我的版本:

public static <E extends Comparable<E>> E getMaxElement(E[][] list) {
    if (list.length <= 0)
        return null;

    E theMaximumElement = list[0][0];

    for (int i = 0; i < list.length; i++)
        for (int j = 0; j < list[i].length; j++)
            if (list[i][j].compareTo(theMaximumElement) > 0)
                theMaximumElement = list[i][j];

    return theMaximumElement;
}