最终的 ArrayList 是什么意思? [英] what is the sense of final ArrayList?

查看:28
本文介绍了最终的 ArrayList 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过将 ArrayList(或其他 Collection)设为 final,我们可以获得哪些优点/缺点?我仍然可以向 ArrayList 添加新元素,删除元素并更新它.但是什么是最终效果呢?

Which advantages/disadvantages we can get by making ArrayList (or other Collection) final? I still can add to ArrayList new elements, remove elements and update it. But what is effect making it's final?

推荐答案

但是什么是最终效果?

But what is effect making it's final?

这意味着您不能重新绑定变量以指向不同的集合实例:

This means that you cannot rebind the variable to point to a different collection instance:

final List<Integer> list = new ArrayList<Integer>();
list = new ArrayList<Integer>(); // Since `list' is final, this won't compile

出于风格的考虑,我将大多数不打算更改的引用声明为 final.

As a matter of style, I declare most references that I don't intend to change as final.

我仍然可以向 ArrayList 添加新元素,删除元素并更新它.

I still can add to ArrayList new elements, remove elements and update it.

如果您愿意,您可以使用 Collections.unmodifiableList():

If you wish, you can prevent insertion, removal etc by using Collections.unmodifiableList():

final List<Integer> list = Collections.unmodifiableList(new ArrayList<Integer>(...));

这篇关于最终的 ArrayList 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆