简体   繁体   中英

Can you use Math.max with an array?

package prova1;

import javax.swing.JOptionPane;

/**
 *
 * @author OOO
 */
public class Prova1 {

    public static void main(String[] args) {
        int array[] = new int[10];
        for (int i = 0; i < array.length; i++) {
            String input = JOptionPane.showInputDialog("Insert number");
            array[i] = Integer.parseInt(input);
        }

        JOptionPane.showMessageDialog(null, Math.max(array));

    }

}

Can you use Math.max with an array?

No, but...

If you're using Java 8, you can use streams :

Arrays.stream(array).max().getAsInt()

Otherwise you can write a simple utility method to do it for you:

public static int max(int... array) {
    if (array.length == 0) {
        // ...
    }

    int max = array[0];

    for (int a : array) {
        if (a > max)
            max = a;
    }

    return max;
}
 // Initializing array of integers 
        Integer[] num = { 2, 4, 7, 5, 9 }; 

  // using Collections.max() to find minimum element 
        // using only 1 line. 
int max = Collections.max(Arrays.asList(num)); 

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