Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why/How does returning a "locally instantiated array" work in Java?

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?

like image 326
uTubeFan Avatar asked Dec 06 '25 04:12

uTubeFan


1 Answers

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.

like image 156
rgettman Avatar answered Dec 07 '25 18:12

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!