简体   繁体   中英

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

How can ı write this code well? Is it true?

I want to find the maximum element. I am not good at Generics in java.

There are two issues in your code:

  • The Comparable::compareTo method doesn't return boolean but int . Here is the description of the method:

    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.

  • You cannot instantiate the generic object such as new E() . Check Instantiating generics type in java .

This is a way to go:

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
}

The only condition is that an element list[0][0] exists, ie the arrays are not empty. Otherwise, you should modify the solution to use Optional<E> since the maximum is not always found (empty arrays).

As of Java 8, there is a simple way to handle such use cases using :

Optional<E> optionalmaximum = Arrays.stream(list)                    // Stream<E[]>
                                    .flatMap(Arrays::stream)         // Stream<E>
                                    .max(Comparator.naturalOrder()); // Optional<E>

This is my version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM