【问题标题】:What does it mean for a collection to be final in Java? [duplicate]集合在 Java 中是最终的意味着什么? [复制]
【发布时间】:2014-10-22 04:40:26
【问题描述】:

在 Java 中将集合声明为 final 是什么意思?是不是不能再添加元素了?是不是已经存在的元素无法更改?是别的吗?

【问题讨论】:

标签: java collections immutability final


【解决方案1】:

您对 finalimmutable 对象感到困惑。

final --> 您不能将 reference 更改为集合(对象)。您可以修改引用指向的集合/对象。您仍然可以将元素添加到集合中

immutable --> 您不能修改引用指向的集合/对象的内容。您不能将元素添加到集合中。

【讨论】:

    【解决方案2】:

    没有。它只是意味着不能更改引用。

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

    【讨论】:

      【解决方案3】:

      你不能这样做,参考是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

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

      【讨论】:

        【解决方案4】:

        将变量设为 final 可确保您在分配对象引用后无法重新分配它。 如果您将 final 关键字与 Collections.unmodifiableList 的使用结合起来,您将获得您所描述的行为:

        final List fixedList = Collections.unmodifiableList(someList);
        

        这导致fixedList指向的列表不能被改变。它仍然可以通过 someList 引用进行更改(因此请确保它在此分配之后超出范围。)

        更简单的例子是使用 Rainbow 类在 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);
            }
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-01-10
          • 1970-01-01
          • 2012-05-02
          • 2020-09-24
          • 2013-06-05
          • 1970-01-01
          • 1970-01-01
          • 2017-06-03
          • 2020-07-02
          相关资源
          最近更新 更多