I have a class which maintains a list of features of the class. These features change infrequently compared to the reads. The reads are almost always iterations through the feature list. Because of this, I'm using a CopyOnWriteArrayList
.
I want to have a function like this:
function Feature[] getFeatures() {
.. implementation goes here ..
}
I admit, the reason may be a bit of laziness. I'd like to write code like this:
for (Feature f: object.getFeatures()) {
.. do something interesting ..
}
rather than this:
Iterator<Feature> iter = object.getFeatureIterator();
while (iter.hasNext()) {
Feature f = iter.next();
.. do something interesting ..
}
The main question is - am I being lazy here? I'm going to follow this pattern a lot, and I think the first chunk of code is far easier to maintain. Obviously, I would never change the underlying array, and I would put this in the documentation.
What is the proper way to handle this situation?