更新时间:2022-12-24 09:26:09
声明静态最终公开
字段通常是类常量的标志。对于原始类型(整数,双精度等)和不可变类,如字符串和 java.awt.Color
,它完全没问题。对于数组,问题是即使数组引用是常量,数组的元素仍然可以更改,因为它是一个字段,更改是无人看管的,不受控制的,通常是不受欢迎的。
Declaring static final public
fields is usually the hallmark of a class constant. It's perfectly fine for primitive types (ints, doubles etc..), and immutable classes, like strings and java.awt.Color
. With arrays, the problem is that even though the array reference is constant, the elements of the array can still be changed, and as it's a field, changes are unguarded, uncontrolled, and usually unwelcome.
为了解决这个问题,数组字段的可见性可以限制为私有或包私有,因此在查找可疑修改时需要考虑较小的代码体。或者,通常更好的方法是将阵列一起取消并使用列表或其他适当的集合类型。通过使用集合,您可以控制是否允许更新,因为所有更新都通过方法进行。您可以使用 Collections.unmodifiableList()
包装集合来阻止更新。但请注意,即使集合是不可变的,您还必须确保存储在其中的类型也是不可变的,否则将会重新出现对所谓常量的未经请求的更改的风险。
To combat this, the visibility of the array field can be restricted to private or package private, so you have a smaller body of code to consider when looking for suspicious modification. Alternatively, and often better, is to do away with the array together and use a 'List', or other appropriate collection type. By using a collection, you control if updates are allowed, since all updates go through methods. You can prevent updates by wrapping your collection using Collections.unmodifiableList()
. But beware that even though the collection is immutable, you must also be sure that the types stored in it are also immutable, or the risk of unsolicited changes on a supposed constant will reappear.