简体   繁体   中英

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?

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.

Neither will be optimal. Roughly you want...

public class ModelList {
    private List<Integer> list;

    ModelList() {
        this.list = new ArrayList<Integer>();
    }

    ModelList(final List<Integer> list) {
        this.list = list;
    }

    public ArrayList<Integer> getList {
       return new ArrayList<Integer>(list); // Send back a copy, to make Immutable
    }
}

The problem with the first one is that everytime you want to update your list, you need to create a new list, get the list from your model, add your element and set the new list to your model.

The second one allow you to do it without the need to get the list and reset it after !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM