使用final关键字声明List字段 [英] Declaring a List field with the final keyword

查看:179
本文介绍了使用final关键字声明List字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个类中有以下语句,其中 Synapse 是一个抽象类型:

If I have the following statement within a class where Synapse is an abstract type:

private final List<Synapse> synapses;

final 允许我仍然能够更改列表 Synapse 对象的状态,但阻止我添加新的 Synapse 对象列表?如果我错了,你可以解释一下 final 正在做什么,以及何时我应该使用关键字 final

Does final allow me to still be able to change the state of the Synapse objects in the List, but prevent me from adding new Synapse objects to the list? If I am wrong, could you please explain what final is doing and when I should be using the keyword final instead.

推荐答案

不,final关键字不会使列表或其内容不可变。如果你想要一个不可变的List,你应该使用:

No, the final keyword does not make the list, or its contents immutable. If you want an immutable List, you should use:

List<Synapse> unmodifiableList = Collections.unmodifiableList(synapses);

最终关键字的作用是阻止您为synapses变量分配新值。即,你不能写:

What the final keyword does is prevent you from assigning a new value to the 'synapses' variable. I.e., you cannot write:

final List<Synapse> synapses = createList();
synapses = createNewList();

但是,你可以这样写:

List<Synapse> synapses = createList();
synapses = createNewList();

这篇关于使用final关键字声明List字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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