The following code snippet seems to work for me exactly as I want:
public CharSequence[] getAllCities() {
String selectQuery = "select " + COLUMN_CITY + " from " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
CharSequence[] cities = new CharSequence[cursor.getCount()];
if (cursor.moveToFirst()) {
int numColumns = cursor.getColumnCount();
int i=0;
do {
cities[i++] = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return cities;
}
That is, the caller gets valid values returned:
CharSequence[] wowthiswillneverworkincpp = database.getAllCities();
But... isn't this going to bite me in some unexpected moment, when the garbage collector kicks in?
If not, what feature in the Java language guarantees that this locally instantiated array will remain valid throughout its use? Am I correct to assume that as long as it is assigned somewhere (i.e. "referenced by"), it will not be wiped clean by the GC?
It doesn't matter if an object is instantiated locally or at any other place. If something has a reference to it, either locally (cities), or assigned from the return of a method (wowthiswillneverworkincpp), then the garbage collector will not wipe it clean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With