Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

Keeping a reference to a list

Hi,

I have some class that loads an array list. I want to let another class instance reference it, but don't want to make a whole copy of it. Something like:

class Loader {
    public void Load()
    {
         m_List.add(new something());
    }
    ArrayList<something> m_List;
}

class Other {

     public void SetListReference(ArrayList<something> theList)
     {
           // just want to keep a reference to theList here.
          m_ListRef = theList;
     }
     ArrayList<something>& m_ListRef;
}


Something like that,

Thanks
ASKER CERTIFIED SOLUTION
Avatar of contactkarthi
contactkarthi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dankuck
dankuck

In Java, all object variables are references.

The code you have supplied would work if you remove the C++ ampersand:

ArrayList<something>& m_ListRef;

becomes

ArrayList<something> m_ListRef;

The code in SetListReference will not copy the ArrayList elements into a new ArrayList, it will just put the original ArrayList reference into the new variable m_ListRef.  Then any changes you make to the ArrayList within class Other will be reflected when class Loader uses the ArrayList.
You'll need to remove the & on contactkarthi's line 22.