Java ArrayList of its own type in constructor

Discussion in 'Mac Programming' started by mmmdreg, Sep 4, 2010.

  1. macrumors 65816

    mmmdreg

    Joined:
    Apr 14, 2002
    Location:
    Sydney, Australia
    #1
    I'm wondering if there's an issue with keeping an ArrayList of objects of the type defined in the same class.

    I've implemented the following, and with some test data it works fine.. except I get a Netbeans warning "leaking this in constructor"

    I can't get much info on this error.. does anyone have any thoughts?

    For the record, it's not a serious program or anything.. I was just wondering if it could be done.

    Code:
    public class Widget {
      // some vars...
      private static ArrayList<Widget> widgetList = new ArrayList<Widget>();
    
      public Widget {
        //set some stuff...
        widgetList.add(this);
      }
    }
    Thanks as always guys =)
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Syntactically that is fine. I think the leaking message is coming about as you can never remove the reference to the newly created Widget so it will never get garbage collected.
     
  3. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    The compiler (javac, not NetBeans) is warning you that you are letting this out into the wild before initialization of your object is complete. In this case it's not a big deal, but the warning is to prevent manipulation/use of an object before its initialization is complete. Imagine you passed this to a printDescription method that called description on your object in your constructor before you had set your fields. The description would be nonsense.

    To your original question, it's fine to have an instance or collection of the same type as a member of a class. Some problems (linked list, trees) could not be solved without this.

    -Lee

    Edit: thought it might be nice to suggest a way around this. You could make a static factory method (newWidget, etc.) that builds a new Widget, adds it to your ArrayList, then returns the new Object.
     
  4. thread starter macrumors 65816

    mmmdreg

    Joined:
    Apr 14, 2002
    Location:
    Sydney, Australia

Share This Page