我如何获得潜在的静态数组了在Java的CopyOnWriteArrayList的? [英] How do I get the underlying static array out of a CopyOnWriteArrayList in Java?
问题描述
我有保留的类的功能列表的类。这些特性的变化很少相比读取。在读取几乎都是通过功能列表迭代。正因为如此,我使用的CopyOnWriteArrayList
。
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
.
我想有这样的功能:
function Feature[] getFeatures() {
.. implementation goes here ..
}
我承认,其原因可能有点懒惰。我想写code是这样的:
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 ..
}
而不是这样的:
Iterator<Feature> iter = object.getFeatureIterator();
while (iter.hasNext()) {
Feature f = iter.next();
.. do something interesting ..
}
主要的问题是 - 我在偷懒吗?我会遵循这个模式有很多,我想code的第一大块是更容易维护。很显然,我永远不会改变底层的数组,我会把这个文档中
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?
推荐答案
只要打电话给方法的toArray名单上:
Just call the toArray method on the list:
public Feature[] getFeatures() {
return this.featureList.toArray(new Feature[this.featureList.size()]);
}
注意的foreach语法可以与所有了Iterable对象使用和列表是可迭代,所以你可以只是
Note that the foreach syntax can be used with all the Iterable objects, and List is Iterable, so you could just have
public List<Feature> getFeatures() {
return this.features;
}
和使用相同的foreach循环。如果你不希望调用者修改的内部列表,返回列表的不可修改视图:
and use the same foreach loop. If you don't want the callers to modify the internal list, return an unmodifiable view of the list:
public List<Feature> getFeatures() {
return Collections.unmodifiableList(this.features);
}
这篇关于我如何获得潜在的静态数组了在Java的CopyOnWriteArrayList的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!