2014-10-22 94 views
6

集合在Java中声明为最终意味着什么?是不是可以添加更多元素?是否已经存在的元素不能改变?还有别的吗?集合在Java中最终是什么意思?

+2

这意味着它是引用(列表的)不能改变 – MadProgrammer 2014-10-22 04:41:34

+0

另请参见:[什么是最终的ArrayList的意义?](http://stackoverflow.com/q/10750791/697449),[用一个列表字段声明最终关键字](http://stackoverflow.com/q/13079365/697449),[Java final modifier](http://stackoverflow.com/q/4012167/697449) – 2014-10-22 04:51:13

回答

7

不,这只是表示参考不能更改。

final List list = new LinkedList(); 

.... 
list.add(someObject); //okay 
list.remove(someObject); //okay 
list = new LinkedList(); //not okay 
list = refToSomeOtherList; //not okay 
3

你得到最后不变对象之间的混淆。

final - >不能将参考更改为集合(Object)。您可以修改集合/对象的参考点。您仍然可以将元素添加到集合

immutable - >您不能修改集合/对象的内容参考点。您无法将元素添加到集合中。

1

你不能做到这一点,引用是FINAL

final ArrayList<Integer> list = new ArrayList<Integer>(); 
    ArrayList<Integer> list2 = new ArrayList<Integer>(); 
    list=list2;//ERROR 
    list = new ArrayList<Integer>();//ERROR 

JLS 4.12.4

一旦最终的变数已被分配,它总是包含相同 值。 如果最后一个变量持有对某个对象的引用,则可以通过该对象上的操作更改该对象的状态,但该变量将始终引用同一个对象。

1

使变量最终确保在赋值后不能重新分配该对象引用。 F你在使用Collections.unmodifiableList的结合final关键字,您戈behavi

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); 
    } 
    } 
}