As indicated by the icus, the fields argument in the constructor can be changed outside the class. It may also be a "non-standard" List implementation. Thus,
this.fields = fields;
should be changed to
this.fields = new ArrayList<Field>(fields);
or maybe
this.fields = Collections.unmodifiableList(new ArrayList<Field>(fields));
There are pros and cons to creating an immutable list box. First of all, it says what you mean. It prevents errors / maintenance engineers. Allocation is a bit and a miss - you do not allocate each time you receive it; Distributions are optimized (potentially analyzed analysis); having objects hanging around is not a good idea because it slows down garbage collection (and consumes memory to a much lesser extent).
Also do all the classes and fields - say what you mean, and there are some subtleties.
The "add" methods are fine. Take a look at BigInteger , say it (although ignore some of its features!).
A somewhat controversial point of view is that everything that get in those access methods in an immutable class is a nuisance. Remove get .
Creating a private constructor and adding a static creation method named of adds a bit, but you almost never need a βnewβ object. Type inference is also allowed before we get the diamond operator currently in JDK7. private constructors also allow you to remove copy variables when creating a new instance in addField and removeField .
equals , hashCode and maybe toString nice to have. Although the API has YAGNI vs construct interfaces (the concept, not the Java keyword).
source share