【问题标题】:Is it required to nullify ArrayList before recreating an object?在重新创建对象之前是否需要使 ArrayList 无效?
【发布时间】:2013-09-18 09:46:00
【问题描述】:

我不确定在使用 arraylist 时它是否会消耗更多的内存。浏览以下代码块时我很困惑:

headerRow = new ArrayList<>();
headerRow.add("");
xlHeader.add(headerRow);

// headerRow = null;                     //<----- This is the line of confusion.
headerRow = new ArrayList<>();

headerRow 是否应该被取消?

添加到 headerRow 的空白字符串对象 ("") 会发生什么?

【问题讨论】:

    标签: java object memory


    【解决方案1】:

    headerRow 将引用新创建的ArrayList,旧的将被注册到垃圾收集。

    因此,不需要作废。

    还有,

    headerRow = new ArrayList<>(); // in JDK 7
    

    而不是

    headerRow = new ArrayList();
    

    是一个正确的实例化语法。

    【讨论】:

    • 在这种特殊情况下,由于xlHeader.add(headerRow);,它可能有资格进行GC。并且 xlHeader 是可访问的。
    【解决方案2】:

    这不是必需的,它将引用新创建的对象。变量headerRow 将引用新创建的ArrayList

    所以你可以直接使用headerRow = new ArrayList();

    【讨论】:

      【解决方案3】:

      你只是使用

      headerRow = new ArrayList();
      

      JVM管理它之前无需取消它。

      而在前两行代码中

      List<String> headerRow = new ArrayList<String>();
      headerRow = new ArrayList();
      

      第二行是多余的,不用写headerRow = new ArrayList();

      因为你已经在前一行初始化了。

      【讨论】:

        【解决方案4】:

        我不知道你为什么这样做:

        List<String> headerRow = new ArrayList<String>();
        // First one is correct; lose the line that follows.
        headerRow = new ArrayList();
        

        【讨论】:

          【解决方案5】:

          此操作对性能没有任何影响。

          当我们以控制的形式使用它时,我们可以将 null 设置为引用,以不再执行操作。

          例如

             Closable stream = getStream();
          
            try {
              stream.close();
              stream = null;
            catch(Exception e) {
              log(e);
            } finally {
              if(stream != null) {
                try { stream.close(); } catch(Exception empty) {}
              }
            }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-07-11
            • 1970-01-01
            • 1970-01-01
            • 2018-11-16
            • 1970-01-01
            • 2011-10-14
            • 2017-04-23
            相关资源
            最近更新 更多