Read Sean

Read me, read Sean.
posts - 508, comments - 655, trackbacks - 9, articles - 4

[Jakarta Commons笔记] 代码范例 - ArrayUtils

Posted on 2005-07-30 11:36 laogao 阅读(3577) 评论(0)  编辑  收藏 所属分类: On Java

 

数组是我们经常需要使用到的一种数据结构,但是由于Java本身并没有提供很好的API支持,使得很多操作实际上做起来相当繁琐,以至于我们实际编码中甚至会不惜牺牲性能去使用Collections API,用Collection当然能够很方便的解决我们的问题,但是我们一定要以性能为代价吗?ArrayUtils帮我们解决了处理类似情况的大部分问题。来看一个例子:

 

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);

 

    }

 

}

 

以下是运行结果:

 

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

 

这段代码说明了我们可以如何方便的利用ArrayUtils类帮我们完成数组的打印、查找、克隆、倒序、以及值型/对象数组之间的转换等操作。如果想了解更多,请参考Javadoc

 

 


只有注册用户登录后才能发表评论。


网站导航: