Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mmmdreg

macrumors 65816
Original poster
Apr 14, 2002
1,393
0
Sydney, Australia
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 =)
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
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.
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.