三段基本的java程序

本文通过三个不同Java程序的实例对比,展示了在使用List存储自定义对象时,如何正确地进行对象管理和引用释放,以避免潜在的内存泄漏问题。文章深入剖析了每种情况的行为差异及其背后的原因。

看看下面的三个程序运行的效果,有点意思:

1)正确的程序
public class MyTest {
 public static void main(String[] args)throws Exception
 {
  MyTest myTest=new MyTest();
  List list=new ArrayList();
  
  MyObject t;
  for(int i=0;i<3;i++)
  {
   t=myTest.new MyObject();
   t.setID(i);
      list.add(t);     
  }
  t=null;
  
  for(int i=0;i<3;i++)
  {
   System.out.println(((MyObject)(list.get(i))).getID());
  }
  
 }
 class MyObject
 {
  long iD;
  
  /**
   * @return 返回 iD。
   */
  public long getID() {
   return iD;
  }
  /**
   * @param id 要设置的 iD。
   */
  public void setID(long id) {
   iD = id;
  }
 }

}

2)错误的程序
public class MyTest {
 public static void main(String[] args)throws Exception
 {
  MyTest myTest=new MyTest();
  List list=new ArrayList();
  
  MyObject t=myTest.new MyObject();
  for(int i=0;i<3;i++)
  {   
   t.setID(i);
      list.add(t);     
  }
  t=null;
  
  for(int i=0;i<3;i++)
  {
   System.out.println(((MyObject)(list.get(i))).getID());
  }
  
 }
 class MyObject
 {
  long iD;
  
  /**
   * @return 返回 iD。
   */
  public long getID() {
   return iD;
  }
  /**
   * @param id 要设置的 iD。
   */
  public void setID(long id) {
   iD = id;
  }
 }

}

3)正确但不太好的程序
public class MyTest {
 public static void main(String[] args)throws Exception
 {
  MyTest myTest=new MyTest();
  List list=new ArrayList();
  
  for(int i=0;i<3;i++)
  {
   MyObject t=myTest.new MyObject();
   t.setID(i);
      list.add(t);
      t=null;
  }
 
  
  for(int i=0;i<3;i++)
  {
   System.out.println(((MyObject)(list.get(i))).getID());
  }
  
 }
 class MyObject
 {
  long iD;
  
  /**
   * @return 返回 iD。
   */
  public long getID() {
   return iD;
  }
  /**
   * @param id 要设置的 iD。
   */
  public void setID(long id) {
   iD = id;
  }
 }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值