从Cursor创建一个数组

时间:2014-06-06 12:27:02

标签: java arrays cursor

以下两种方法(两者都覆盖long[] mArray),哪种方法更受欢迎?

第一种方法遍历Cursor,为每一行调用ArrayList.add(),然后遍历ArrayList以将值复制到数组。

第二种方法迭代Cursor两次。一次,每次调用size++来计算行数,然后再次将值复制到数组中。

public void arrayFromCursor1(Cursor cursor) {

    // create a temp ArrayList to add to as we don't
    // know how many rows are in the cursor
    List<Long> list = new ArrayList<Long>();
    // iterate over the cursor
    if (cursor.moveToFirst()) {
        do {
            list.add(cursor.getLong(cursor.getColumnIndex("column_name")));
        } while (cursor.moveToNext());
        // create a long[] of appropriate length and copy values from the
        // ArrayList using a for loop
        final int size = list.size();
        mArray = new long[size];
        for (int i = 0; i < size; i++) {
            mArray[i] = list.get(i);
        }
    }
}

public void arrayFromCursor2(Cursor cursor) {

    // no need for a temp ArrayList this time
    // iterate over the cursor simply counting the rows
    if (cursor.moveToFirst()) {
        int size = 0;
        do {
            size++;
        } while (cursor.moveToNext());
        // create a long[] of appropriate length and iterate over the
        // cursor again, this time with a for loop copying values to the array
        mArray = new long[size];
        cursor.moveToFirst();
        for (int i = 0; i < size; i++) {
            mArray[i] = cursor.getLong(cursor.getColumnIndex("column_name"));
            cursor.moveToNext();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我想出了一个从Cursor创建数组的干净简单的解决方案。这在将数组存储在外键表中时非常有用,并且可以使用基元。

public long[] arrayFromCursor(Cursor cursor) {

    int length = cursor.getCount();
    long[] array = new long[length];

    if (cursor.moveToFirst()) {
        for (int i = 0; i < length; i++) {
            array[i] = cursor.getLong(cursor.getColumnIndex("column_name"));
            cursor.moveToNext();
        }
    }
    return array;
}