PDA

View Full Version : Java ArrayList of its own type in constructor




mmmdreg
Sep 4, 2010, 09:45 AM
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.


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
Sep 4, 2010, 09:55 AM
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
Sep 4, 2010, 09:58 AM
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.

mmmdreg
Sep 5, 2010, 01:19 AM
Thanks guys, always helpful! =)