通过将 ArrayList(或其他 Collection)设为 final,我们可以获得哪些优势/劣势?我仍然可以向 ArrayList 添加新元素、删除元素并对其进行更新。但是最终的效果是什么?
最佳答案
But what is effect making it's final?
这意味着您不能重新绑定(bind)变量以指向不同的集合实例:
final List<Integer> list = new ArrayList<Integer>();
list = new ArrayList<Integer>(); // Since `list' is final, this won't compile
就风格而言,我将大部分不打算更改的引用声明为 final
。
I still can add to ArrayList new elements, remove elements and update it.
如果您愿意,您可以使用 Collections.unmodifiableList()
来防止插入、移除等。 :
final List<Integer> list = Collections.unmodifiableList(new ArrayList<Integer>(...));
关于java - final ArrayList 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10750791/