ArrayUtils 在 commons-lang.jar 里
maven dependency:
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
import org.apache.commons.lang.ArrayUtils;
// 用 ArrayUtils.add 给数组添加一个元素
String[] arr = { "2018-4-28", "2019-4-28" };
String name = "1840-4-28";
arr = ( String[] ) ArrayUtils.add( arr, name );
for ( int i = 0; i < arr.length; i++ ) {
System.out.println( arr[ i ] );
}
-----------------------------------------------------------
这个 ArrayUtil.add 方法的源码如下:
// 给数组添加一个元素,来自 ArrayUtils
public static Object[] addOfArrayUtils( Object[] array, Object element ) {
Class type;
if (array != null){
type = array.getClass();
} else if (element != null) {
type = element.getClass();
} else {
type = Object.class;
}
Object[] newArray = null;
if ( array != null ) {
int arrayLength = Array.getLength( array);
Object newArrayTemp = Array.newInstance( array.getClass().getComponentType(), arrayLength + 1 );
System.arraycopy( array, 0, newArrayTemp, 0, arrayLength );
newArray = ( Object[] ) newArrayTemp;
} else {
newArray = ( Object[] ) Array.newInstance( type, 1 );
}
newArray[ newArray.length - 1 ] = element;
return newArray;
}
-----------------------------------------------------------
org.apache.commons.lang 里有用的还有 StringUtils
import org.apache.commons.lang.StringUtils;
StringUtils 里的 isBlank 和 isNotBlank 的源码如下:
// isBlank of StringUtils
public static boolean isBlank( String str ) {
int strLen;
if ( str == null || ( strLen = str.length() ) == 0 ) {
return true;
}
for ( int i = 0; i < strLen; i++ ) {
if ( ( Character.isWhitespace( str.charAt( i ) ) == false ) ) {
return false;
}
}
return true;
}
// isNotBlank of StringUtils
public static boolean isNotBlank( String str ) {
return !isBlank( str );
}
-----------------------------------------------------------
这个 org.apache.commons.lang 里的 CollectionUtils 不好用。
要用 org.springframework.util.CollectionUtils,里面的 isEmpty 的源码如下:
// isEmpty( collection ) from org.springframework.util.CollectionUtils
public static boolean isEmpty( Collection collection ) {
return ( collection == null || collection.isEmpty() );
}
// isEmpty( map ) from org.springframework.util.CollectionUtils
public static boolean isEmpty( Map map ) {
return ( map == null || map.isEmpty() );
}
public static boolean isNotEmpty( Collection collection ) {
return !isEmpty( collection );
}
public static boolean isNotEmpty( Map map ) {
return !isEmpty( map );
}