首页 新闻 会员 周边

java返回数组的内存问题

0
悬赏园豆:20 [已解决问题] 解决于 2012-10-25 09:42

大家好!
c++中,一个函数内部这样写:
int* fun(){
  int nums[] = { 4,5,6};   
  return nums;
} 那么除非nums加static修饰,否则函数结束后nums的内存会被释放,外部不能再用。

Java中这样写:
  public static int[] ByNew()   
  {   
  int[] nums= new int[] {   
  1,2,3   
  };   
  return nums;   
  }
当然没问题,new出来的数组不用担心函数结束后内存被释放

但是如果这样写呢:
  public static int[] ByStaticInit()   
  {   
    
  int nums[] = { 4,5,6};   
  return nums;   
  }   
我担心数组存放在栈内存,函数结束后内存被释放,不知道是不是这样?请大家指教。
(尽管下面测试代码运行没问题)

public class StaticInitArry   
{   
    
  public static int[] ByNew()   
  {   
  int[] nums= new int[] {   
  1,2,3   
  };   
  return nums;   
  }   
  public static int[] ByStaticInit()   
  {   
    
  int nums[] = { 4,5,6};   
  return nums;   
  }   
  public static void main(String[] args)   
  {   
  int nums[] =ByNew();   
  for(int i=0;i<nums.length;i++)   
  {   
  System.out.println(nums[i]);   
  }   
  //////////////////////////////////////////   
  int nums2[] =ByStaticInit();   
  for(int i=0;i<nums2.length;i++)   
  {   
  System.out.println(nums2[i]);   
  }   
 
    
  }   
}   
 
/*  
输出:  
1  
2  
3  
4  
5  
6  
*/

autumn20080101的主页 autumn20080101 | 初学一级 | 园豆:184
提问于:2012-10-24 09:20
< >
分享
最佳答案
0

java有垃圾回收机制,不用担心不会收回,一般也不用人工干预。

收获园豆:20
向往-SONG | 老鸟四级 |园豆:4853 | 2012-10-24 09:35

这样写呢:
  public static int[] ByStaticInit()   
  {   
    
  int nums[] = { 4,5,6};   
  return nums;   
  }   
我担心数组存放在栈内存,函数结束后内存被释放

ps:我不是担心不释放,而是不懂 

int nums[] = { 4,5,6};  

这种方式,数组是否放在栈内存,是否在函数结束后内存被释放

autumn20080101 | 园豆:184 (初学一级) | 2012-10-24 09:38

如果函数结束后内存被释放,就不能在函数外继续使用了

autumn20080101 | 园豆:184 (初学一级) | 2012-10-24 09:40

@autumn20080101: 

基本类型(原始数据类型)对象才会放栈里,数组不是,在函数内定义的变量是不能在外面使用的。

向往-SONG | 园豆:4853 (老鸟四级) | 2012-10-24 09:53

@向往-SONG:就是说 

 public static int[] ByStaticInit()   
  {   
    
  int nums[] = { 4,5,6};   
  return nums;   
  } 等同于

int[] nums= new int[] { 
1,2,3 
}; 
return nums; 都是放在堆上。

再问一下

public static Integer ByNew()
{
Integer num = new Integer(15);
return num;
}与

public static Integer NotByNew()
{
Integer num = 15;
return num;
}

后者需要担心函数结束后内存释放失效吗?

 

autumn20080101 | 园豆:184 (初学一级) | 2012-10-24 11:56

@autumn20080101: 

不会,不要把C++的东西套过来,所有C++关于内存释放的问题,在java中都不适应,没有指针,没有传值传引用之分(除原始数据类型传值其它都是引用)。。。

学java先把C++的东西忘掉吧。

向往-SONG | 园豆:4853 (老鸟四级) | 2012-10-24 12:22
其他回答(2)
0

不用担心会溢出,有回收机制把它回收了,能打印出你想要的结果!

若雪封尘 | 园豆:463 (菜鸟二级) | 2012-10-24 11:22
0

Java自动管理栈和堆,程序员不能直接地设置栈或堆.你可以搜索一下java的四种引用类型。一旦对象没有被引用时会自动被回收

旺仔小小小馒头 | 园豆:196 (初学一级) | 2012-10-24 11:38

就是说我不用管数组是放在栈上还是堆上,只要还有对其的引用存在,就不会被释放,对吧。

支持(0) 反对(0) autumn20080101 | 园豆:184 (初学一级) | 2012-10-24 11:49

@autumn20080101: 对

支持(0) 反对(0) 旺仔小小小馒头 | 园豆:196 (初学一级) | 2012-10-24 11:51
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册