Steve Chambers Steve Chambers - 1 month ago 17
Java Question

How to implement the getter/setter for a Collection field in a Java class?

I'm creating a JavaBean that contains a List and can think of two possibilities:

public class JavaBeanWithSettableList {
private List<Integer> list;
public List<Integer> getList {
return list;
}
public void setList(final List<Integer> list) {
this.list = list;
}
}


...or...

public class JavaBeanWithUnsettableList {
private List<Integer> list = new ArrayList<Integer>();
public List<Integer> getList {
return this.list;
}
// No setter - need to use list.add(), list.remove() etc.
}


The second one I've seen used on another project - it seems better but I'm not sure where this design came from. Could anyone point me towards an article naming the pattern and/or describing its benefits?

Answer

There is no name for this pattern. The first one is just a class with a List and the second one is a list which is created internally.

Generally the less state and the more immutability you have in your classes are the better. The reason for this is that if you have less state you have less chance of producing an error.

In your case if for example you use the first approach then you can't make sure that someone else does not set another list to your model. In the second case you can't make sure that someone will not call clear() on your list.

In the end it all depends on your use case. If you want your class to hold a list but you don't want any changes in the future you should use an immutable list. Otherwise restrict the mutability as much as you can.