Question

I have a class with as private List<String> children; which is currently initialized in the constructor but this is not always needed and I want to initialize it only when some other function need it.

The whole point is to rework current implementation without changing to much code.

I know how to do it in other languages, but Java knowledge is quite limited, so far.

Was it helpful?

Solution

To spell it out, this is one way of accomplishing it:

public class Whatever 
{
    private List<String> children;

    public List<String> getChildren
    {
        if ( children == null ) { children = new ArrayList<String>(); }
        return children;
    }
    ...
}

Also, remember to write eg. addChild( String child ) in terms of the get'er rather than directly accessing the field. And if you're really paranoid and/or in a threaded environment and the creation takes a long time, you might want to make the block synchronized.

OTHER TIPS

You can create it in the getter if children is null. Take care of proper synchronization. If children is not expensive to create and you won't create a massive amount of instances, do it eager. Saves you the hassle.

It is a common practice in java hide member variables of data transfer objects behind accessor methods, the infamous getters and setters of java beans. If you do this, you can add any logic (create list on first call, return imutable lists to external clients, etc.) you want in your `List getChildren() method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top