源码版本
commons-lang3-3.1.jar
function
Provides extra functionality for Java Number classes.
源码介绍
字符串转化成int
/**
* <p>Convert a <code>String</code> to an <code>int</code>,
* returning <code>zero</code> if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, <code>zero</code> is
* returned.</p>
* <pre>
* NumberUtils.toInt(null) = 0
* NumberUtils.toInt("") = 0
* NumberUtils.toInt("1") = 1
* </pre>
* @since 2.1
*/
public static int toInt(String str) {
return toInt(str, 0);
}
/**
* <p>Convert a <code>String</code> to an <code>int</code>,
* returning a default value if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, the default value is
* returned.</p>
* <pre>
* NumberUtils.toInt(null, 1) = 1
* NumberUtils.toInt("", 1) = 1
* NumberUtils.toInt("1", 0) = 1
* </pre>
* @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
/**
* <p>Returns the minimum value in an array.</p>
*
*/
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
/**
* <p>Returns the maximum value in an array.</p>
*/
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;
}
本文介绍了Java中利用commons-lang3库进行字符串到各种基本类型的转换方法,包括int、long等,并提供了数组中的最大值与最小值查找的实现。
158

被折叠的 条评论
为什么被折叠?



