[英]Create an array from 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();
}
}
}
我想出了一個從游標創建數組的干凈,簡單的解決方案。 在將數組存儲在外鍵表中時,這很有用,並且可以與基元一起使用。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.