Java递归时报错:java.lang.StackOverflowError,求解
/**
* xxx 20181018
* 从整形ArrayList source中 抽取n个元素,所构成的组合为 ArrayList<ArrayList<Integer>> result
* @param ArrayList<Integer> source
* @param int n
* @return ArrayList<ArrayList<Integer>> result
*/
public static ArrayList<ArrayList<Integer>> CombinationT(ArrayList<Integer> source,int n)
{ System.out.println("CombinationT(source,n):source.size()="+source.size()+"; n="+n);
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
if(n==1)
{
for(int i=0;i<source.size();i++)
{ Object t=source.get(i);
ArrayList a= new ArrayList();
a.add(t);
result.add(a);
}
}
else if(source.size()==n)
{
result.add(source);
}
else
{
ArrayList<Integer> psource=new ArrayList<Integer>();
//[source.size()-1];
for(int i=0;i<source.size()-1;i++)
{
psource.add(source.get(i));
}
//报错信息所提示的84行代码
result.addAll(CombinationT(psource,n));
ArrayList<ArrayList<Integer>> tmp=CombinationT(psource,n-1);
for(int i=0;i<tmp.size();i++)
{
ArrayList<Integer> rs=new ArrayList<Integer>();
for(int j=0;j<n-1;j++)
{
rs.add(tmp.get(i).get(j));
}
rs.add(source.get(source.size()-1));
result.add(rs);
}
}
return result;
}
上面这个java写的组合方法在多次递归调用CombinationT后出现:
Exception in thread "main" java.lang.StackOverflowError
at com.fh.xt.utils.Combination.CombinationT(Combination.java:84)
at com.fh.xt.utils.Combination.CombinationT(Combination.java:84)
at com.fh.xt.utils.Combination.CombinationT(Combination.java:84)
...
的栈溢出报错,如何修改才能避免栈溢出???
...全文
相关推荐
如何解决java.lang.StackOverflowError
解决java.lang.StackOverflowError
Java中内存异常StackOverflowError与OutOfMemoryError详解
主要介绍了 Java中内存异常StackOverflowError与OutOfMemoryError详解的相关资料,需要的朋友可以参考下
java利用递归调用实现树形菜单的样式
主要给大家介绍了关于java利用递归调用实现树形菜单样式的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Java开发常见错误及解决方案文件
Java开发常见错误及解决方案文件,这里描述的是开发中常见的错误和解决方案,如有需要请下载吧,很有用的,也欢迎大家挑错
java.lang.StackOverflowError(解决方案).md
项目中碰到的,记录一下解决方案


Java SE
