在Java中声明final的集合意味着什么?难道不再添加任何元素吗?是否已经存在的元素无法改变?是别的吗?
答案 0 :(得分:12)
没有。它只是意味着无法更改引用。
final List list = new LinkedList();
....
list.add(someObject); //okay
list.remove(someObject); //okay
list = new LinkedList(); //not okay
list = refToSomeOtherList; //not okay
答案 1 :(得分:6)
您在最终和不可变对象之间感到困惑。
final
- >您无法将引用更改为集合(Object)。您可以修改参考指向的集合/对象。您仍然可以向集合中添加元素
immutable
- >您不能修改引用所指向的Collection / Object的内容。您无法向集合中添加元素。
答案 2 :(得分:3)
你不能这样做,引用是FINAL
final ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
list=list2;//ERROR
list = new ArrayList<Integer>();//ERROR
一旦分配了最终变量,它总是包含相同的变量 值。 如果最终变量包含对象的引用,那么 可以通过对对象的操作来改变对象的状态,但是 变量将始终引用同一个对象。
答案 3 :(得分:2)
使变量最终确保在分配后不能重新分配该对象引用。 如果您将final关键字与Collections.unmodifiableList结合使用,则可以使用行为
final List fixedList = Collections.unmodifiableList(someList);
这导致fixedList指向的列表无法更改。它仍然可以通过someList引用进行更改(因此请确保在此asignment之后它超出范围。)
更简单的例子是使用彩虹类在hashset中添加彩虹颜色
public static class Rainbow {
/** The valid colors of the rainbow. */
public static final Set VALID_COLORS;
static {
Set temp = new HashSet();
temp.add(Color.red);
temp.add(Color.orange);
temp.add(Color.yellow);
temp.add(Color.green);
temp.add(Color.blue);
temp.add(Color.decode("#4B0082")); // indigo
temp.add(Color.decode("#8A2BE2")); // violet
VALID_COLORS = Collections.unmodifiableSet(temp);
}
/**
* Some demo method.
*/
public static final void someMethod() {
Set colors = RainbowBetter.VALID_COLORS;
colors.add(Color.black); // <= exception here
System.out.println(colors);
}
}
}