从列表中的对象的特定字段创建数组

时间:2013-09-19 20:37:16

标签: java android

我不太确定如何恰当地说出来。我有一个对象列表,这些对象具有特定字段的getter。我现在需要从ojbect列表中创建一个数组,但我只需要一个特定的数据。

有没有办法在不使用似乎非常低效的交互器的情况下这样做?

这是在Android应用程序的上下文中。

2 个答案:

答案 0 :(得分:0)

    // our original list
    List<Integer> list = new ArrayList<Integer>();

    // inserting some values
    for(int i = 0;i<100;i++){
        list.add(i);
    }

    // work starts here :

    // select a range of elements based on index
    List<Integer> subList = list.subList(0, 50);
        // list.subList(from index-inclusive,to index-exclusive)

    // create an array to hold your new values
    Integer[] myArray = new Integer[0]; // must initialize

    // assign the part of your original list to this array
    myArray = subList.toArray(myArray);


    // test Result :
    System.out.println(Arrays.toString(myArray));
        // reult :
        /*
         * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
         * 11, 12, 13, 14, 15, 16, 17, 18, 19, 
         * 20, 21, 22, 23, 24, 25, 26, 27, 28, 
         * 29, 30, 31, 32, 33, 34, 35, 36, 37, 
         * 38, 39, 40, 41, 42, 43, 44, 45, 46, 
         * 47, 48, 49]
         */

    // hope this was what you were looking for   

答案 1 :(得分:0)

只是为了结束这个问题 - 问题下方的评论是正确的“答案”。似乎没有更好(或更有效)的方式来做我所问的。