博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
commons-lang3之NumberUtils源码解析
阅读量:4203 次
发布时间:2019-05-26

本文共 2843 字,大约阅读时间需要 9 分钟。

源码版本

commons-lang3-3.1.jar

function

Provides extra functionality for Java Number classes.

源码介绍

字符串转化成int

/** * 

Convert a String to an int, * returning zero if the conversion fails.

* *

If the string is null, zero is * returned.

*
 *   NumberUtils.toInt(null) = 0 *   NumberUtils.toInt("")   = 0 *   NumberUtils.toInt("1")  = 1 * 
* @since 2.1 */public static int toInt(String str) { return toInt(str, 0);}/** *

Convert a String to an int, * returning a default value if the conversion fails.

* *

If the string is null, the default value is * returned.

*
 *   NumberUtils.toInt(null, 1) = 1 *   NumberUtils.toInt("", 1)   = 1 *   NumberUtils.toInt("1", 0)  = 1 * 
* @since 2.1 */public static int toInt(String str, int defaultValue) { if(str == null) { return defaultValue; } try { return Integer.parseInt(str); } catch (NumberFormatException nfe) { return defaultValue; }}

字符串转化成long

public static long toLong(String str) {    return toLong(str, 0L);}public static long toLong(String str, long defaultValue) {    if (str == null) {        return defaultValue;    }    try {        return Long.parseLong(str);    } catch (NumberFormatException nfe) {        return defaultValue;    }}

类似的还有toFloat、toDouble、toByte、toShort

字符串转成Integer

public static Integer createInteger(String str) {    if (str == null) {        return null;    }    // decode() handles 0xAABD and 0777 (hex and octal) as well.    return Integer.decode(str);}

Min in array

/**     * 

Returns the minimum value in an array.

* */public static long min(long[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min;}

Max in array

/** * 

Returns the maximum value in an array.

*/public static long max(long[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max long max = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] > max) { max = array[j]; } } return max;}

Gets the maximum of three int

public static int max(int a, int b, int c) {    if (b > a) {        a = b;    }    if (c > a) {        a = c;    }    return a;}

Gets the minimum of three int

public static int min(int a, int b, int c) {    if (b < a) {        a = b;    }    if (c < a) {        a = c;    }    return a;}

转载地址:http://bnvli.baihongyu.com/

你可能感兴趣的文章