数组工具ArrayUtils
先看下这个类的介绍
Operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]).This class tries to handle null input gracefully. An exception will not be thrown for a null array input. However, an Object array that contains a null element may throw an exception.
简单的说这个工具类加了一些判空操作,对数组为空做了处理,但是数组中存在空元素依然会抛出异常。
举个栗子:
public static String toString(Object array) {
return toString(array, "{}");
}
public static String toString(Object array, String stringIfNull) {
if (array == null) {
return stringIfNull;
}
return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString();
}
当数组为空时会返回"{}"。
还有一个实用的方法nullToEmpty:
public static String[] nullToEmpty(String[] array) {
if (array == null || array.length == 0) {
return EMPTY_STRING_ARRAY;
}
return array;
}
这个方法可以减少判空操作,直接将对象转化为空数组。
当想比较两个数组长度是否相同时可以使用isSameLength:
public static boolean isSameLength(Object[] array1, Object[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
字符串工具StringUtils
trim和strip两个方法略有不同。trim去掉字符串两端的控制符(control characters, char <= 32),如果变为null或"",则返回""。strip则是去掉字符串两端的空白符。
StringUtils.trim(" \b \t \n \f \r ") = ""
StringUtils.strip(" \b \t \n \f \r ") = "\b"
来看下trim方法的实现:
public static String trim(String str) {
return str == null ? null : str.trim();
}
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
//空格的ASCII 值刚好是32
再看下strip的实现
public static String strip(String str) {
return strip(str, null);
}
public static String strip(String str, String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
public static String stripStart(String str, String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND)) {
start++;
}
}
return str.substring(start);
}
//最终判断是根据Character.isWhitespace方法
split方法可以把字符串转换成字符数组,可以指定分隔字符或分隔字符串。
join方法是split方法的逆方法,可以把字符串数组拼接成字符串。
布尔工具类BooleanUtils
negate方法返回与传入值相反的值:
public static Boolean negate(Boolean bool) {
if (bool == null) {
return null;
}
return (bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE);
}