2014-10-22 36 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); 
    } 
    } 
}