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

前端 未结 15 2065
遥遥无期
遥遥无期 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:21

    Using Commons Lang (to convert) + Collections (to min/max)

    import java.util.Arrays;
    import java.util.Collections;
    
    import org.apache.commons.lang.ArrayUtils;
    
    public class MinMaxValue {
    
        public static void main(String[] args) {
            char[] a = {'3', '5', '1', '4', '2'};
    
            List b = Arrays.asList(ArrayUtils.toObject(a));
    
            System.out.println(Collections.min(b));
            System.out.println(Collections.max(b));
       }
    }
    

    Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

提交回复
热议问题