Finding the max/min value in an array of primitives using Java

前端 未结 15 1887
遥遥无期
遥遥无期 2020-11-22 05:09

It\'s trivial to write a function to determine the min/max value in an array, such as:

/**
 * 
 * @param chars
 * @return the max value in the array of chars         


        
15条回答
  •  臣服心动
    2020-11-22 05:30

    Yes, it's done in the Collections class. Note that you will need to convert your primitive char array to a Character[] manually.

    A short demo:

    import java.util.*;
    
    public class Main {
    
        public static Character[] convert(char[] chars) {
            Character[] copy = new Character[chars.length];
            for(int i = 0; i < copy.length; i++) {
                copy[i] = Character.valueOf(chars[i]);
            }
            return copy;
        }
    
        public static void main(String[] args) {
            char[] a = {'3', '5', '1', '4', '2'};
            Character[] b = convert(a);
            System.out.println(Collections.max(Arrays.asList(b)));
        }
    }
    

提交回复
热议问题