Of the following two methods (both of which overwrite long[] mArray), which would be preferred?
The first method iterates over the Cursor, calling ArrayList.add() for each row, then iterates over the ArrayList to copy the values to the array.
The second method iterates over the Cursor twice. Once, calling size++ each time to count the rows, and again to copy the values to the array.
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();
}
}
}
toArraymethod of your list.mArray = list.toArray(new long[list.size()]).