數(shù)組是我們經(jīng)常需要使用到的一種數(shù)據(jù)結(jié)構(gòu),但是由于Java本身并沒(méi)有提供很好的API支持,使得很多操作實(shí)際上做起來(lái)相當(dāng)繁瑣,以至于我們實(shí)際編碼中甚至?xí)幌奚阅苋ナ褂?/span>Collections API,用Collection當(dāng)然能夠很方便的解決我們的問(wèn)題,但是我們一定要以性能為代價(jià)嗎?ArrayUtils幫我們解決了處理類似情況的大部分問(wèn)題。來(lái)看一個(gè)例子:
package sean.study.jakarta.commons.lang;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
public class ArrayUtilsUsage {
public static void main(String[] args) {
// data setup
int[] intArray1 = { 2, 4, 8, 16 };
int[][] intArray2 = { { 1, 2 }, { 2, 4 }, { 3, 8 }, { 4, 16 } };
Object[][] notAMap = {
{ "A", new Double(100) },
{ "B", new Double(80) },
{ "C", new Double(60) },
{ "D", new Double(40) },
{ "E", new Double(20) }
};
// printing arrays
System.out.println("intArray1: " + ArrayUtils.toString(intArray1));
System.out.println("intArray2: " + ArrayUtils.toString(intArray2));
System.out.println("notAMap: " + ArrayUtils.toString(notAMap));
// finding items
System.out.println("intArray1 contains '8'? "
+ ArrayUtils.contains(intArray1, 8));
System.out.println("intArray1 index of '8'? "
+ ArrayUtils.indexOf(intArray1, 8));
System.out.println("intArray1 last index of '8'? "
+ ArrayUtils.lastIndexOf(intArray1, 8));
// cloning and resversing
int[] intArray3 = ArrayUtils.clone(intArray1);
System.out.println("intArray3: " + ArrayUtils.toString(intArray3));
ArrayUtils.reverse(intArray3);
System.out.println("intArray3 reversed: "
+ ArrayUtils.toString(intArray3));
// primitive to Object array
Integer[] integerArray1 = ArrayUtils.toObject(intArray1);
System.out.println("integerArray1: "
+ ArrayUtils.toString(integerArray1));
// build Map from two dimensional array
Map map = ArrayUtils.toMap(notAMap);
Double res = (Double) map.get("C");
System.out.println("get 'C' from map: " + res);
}
}
以下是運(yùn)行結(jié)果:
intArray1: {2,4,8,16}
intArray2: {{1,2},{2,4},{3,8},{4,16}}
notAMap: {{A,100.0},{B,80.0},{C,60.0},{D,40.0},{E,20.0}}
intArray1 contains '8'? true
intArray1 index of '8'? 2
intArray1 last index of '8'? 2
intArray3: {2,4,8,16}
intArray3 reversed: {16,8,4,2}
integerArray1: {2,4,8,16}
get 'C' from map: 60.0
這段代碼說(shuō)明了我們可以如何方便的利用ArrayUtils類幫我們完成數(shù)組的打印、查找、克隆、倒序、以及值型/對(duì)象數(shù)組之間的轉(zhuǎn)換等操作。如果想了解更多,請(qǐng)參考Javadoc。