将实例设置为null或使用new创建新实例

时间:2014-01-08 17:58:59

标签: java

这是:

// Class 'Refresh' inherits class 'Thread'
Thread refresh = new Refresh(paramOne);
...
refresh = null;
refresh = new Refresh(paramTwo);

而且:

// Class 'Refresh' inherits class 'Thread'
Thread refresh = new Refresh(paramOne);
...
refresh = new Refresh(paramTwo);

有相同的结果吗?
是否在现有对象上分配新的类实例会使第一个类实例无效?

3 个答案:

答案 0 :(得分:4)

实际上他们并没有完全相同的结果。

在第一种情况下,如果在构建new Refresh()时抛出异常,则refresh仍为null。在第二种情况下,refresh仍将是第一个构造的对象。

假设new Refresh(paramTwo)没有抛出异常,或者刷新变量在当前上下文之外不可见,那么两者是等价的。

public class Main{

  static class Boom {
    Boom(boolean noBoom) {
    }
    Boom() {
       throw new RuntimeException();
    }
  }

  public static void main(String[] args){
   Boom boom1 = new Boom(true);
   try {
     boom1=null;
     boom1=new Boom();
   } catch (Exception ex) {};
   System.out.println(boom1);

   Boom boom2 = new Boom(true);
   try {
     boom2=new Boom();
   } catch (Exception ex) {};
   System.out.println(boom2);

 }
}

试一试: http://www.tryjava8.com/app/snippets/52cd952fe4b00bdc99e8ab38

结果:

null 
Main$Boom@d35755c

答案 1 :(得分:0)

简短的回答是肯定的。假设没有其他对原始值的引用,那么该值有资格进行垃圾收集。

答案 2 :(得分:0)

没有区别。

refresh = null;

这里多余。它没有任何区别。

写作时

refresh = new Refresh(paramTwo);

无论如何,现有的参考是最重要的。所以不管它以前是什么。天气它是null或仍然持有一些实例并不重要。

相关问题