猿问

赋值问题,菜鸟求助大神啊,这代码什么问题?


为什么这里的combArray是空的而下面
spacer.gifhttp://img.mukewang.com/582b32350001d8df06750437.jpg

这里明明给combArray赋值了呀

http://img.mukewang.com/582b325400012bc906490364.jpg

源代码如下:


import java.util.ArrayList;
import java.util.List;

public class FindCombination {
private int begin, end;// 组合最小、大长度
// number长度的组合集合
private List<CombNode> combArray = new ArrayList<CombNode>();
// begin-end长度的组合集合
private List<List<CombNode>> combBalls = new ArrayList<List<CombNode>>();

public FindCombination(CombNode[] array, int begin, int end) {//初始器
this.begin = begin;
this.end = end;
if (array == null || array.length == 0 || begin > end) {
System.out
.println("wrong,the reason maybe is :\"array==null\" or \"array.length == 0\" or \"begin>end\"");
return;
}
List<CombNode> list = new ArrayList<CombNode>();
for (int length = begin; length <= end; length++) {
combination(array, 0, length, list);
combBalls.add(combArray);
System.out.println("#######");
System.out.print("初始器里combArray:");
for (int i = 0; i < combArray.size(); i++) {
System.out.print(combArray.get(i).getValue() + " ");
}
System.out.println();
System.out.println("#######");
combArray.clear();

}

}
//递归选取元素
private void combination(CombNode[] array, int begin, int length,
List<CombNode> list) {
if (length == 0) {
combArray = list;

for (int i = 0; i < combArray.size(); i++) {
System.out.print(combArray.get(i).getValue() + " ");
}
System.out.println();
return;
}
if (begin == array.length) {
return;
}
list.add(array[begin]);
combination(array, begin + 1, length - 1, list);
list.remove(array[begin]);
combination(array, begin + 1, length, list);
}

public List<CombNode> getXLengthCombination(int length) {//获取x长度的所有组合
if (length < begin || length > end) {
System.out
.println("wrong,the length must be greater than begin and less than end at the same time");
return null;
}
return combBalls.get(length);
}

public void printCombination() {// 打印所有组合
for (int i = 0; i < combBalls.size(); i++) {
for (int j = 0; j < combBalls.get(i).size(); j++) {
System.out.print(combBalls.get(i).get(j).getValue() + " ");
}
System.out.println();
}
}

public static void main(String[] args) {
String[] array = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
// int[] array={1,2,3,4,5,6,7,8,9,10};
CombNode[] cn = new CombNode[10];
for (int i = 0; i < array.length; i++) {
cn[i] = new CombNode(array[i], true);
}
System.out.println("\n***********");
FindCombination fc = new FindCombination(cn, 1, 2);
System.out.println("***********");
System.out.println("通过方法打印");
fc.printCombination();
}
}


Roy_Hatsune
浏览 1107回答 1
1回答

按照自己的节奏前行

你每次将数据放入list的后,此时你的list地址值传给combArray,即此时的combArray就是List,然后你将list的数据删除,嗯,combArray与list指向同一块内存区域,也就是所combArray也删除了数据,最后你的combArray和list依旧指向同一块数据,此时的list为空,comAbrray当然也为空了.最后没有数据,你想输出什么,再就是没搞懂的是,你就是想验证个赋值问题,用得着敲这么长的代码作死吗?基本没人想看...还有,即使你不把combArray.clear()清空,也没有数据的,因为之前就已经没有数据了.觉得自己递归写的好,那就去算法区,不想说你了!!!
随时随地看视频慕课网APP

相关分类

Java
我要回答