从网上扒的代码,我运行测试已经没有问题了,但是有些地方百思不得其解。
在每一次添加孩子集合hashVP后,为什么r和hash两个全局变量也跟着发生了数据变化,并没有对着两个变量进行add,put等操作啊。
public static JSONArray listToTree(JSONArray arr,String id,String pid,String child){
JSONArray r = new JSONArray();
JSONObject hash = new JSONObject();
//将传入的数组arr转为Object的hash形式
for(int i=0;i<arr.size();i++){
JSONObject json = (JSONObject) arr.get(i);
//hash列表key值为id,value值为一条json
hash.put(json.getString(id), json);
}
//遍历传入的数组arr
for(int j=0;j<arr.size();j++){
//获取单条数组记录aVal
JSONObject aVal = (JSONObject) arr.get(j);
//单条数组aVal的pid在Object列表中是否存在key值所对应的数据
JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
//如果存在,则说明这条aVal有父节点,将它添加到孩子节点的集合中
if(hashVP!=null){
/******************************疑问部分*******************************/
检查父节点hashVP是否有child属性。
if(hashVP.get(child)!=null){
//如果存在,获取child列表,追加一条aVal
JSONArray ch = (JSONArray) hashVP.get(child);
ch.add(aVal);
//将child列表重新添加
hashVP.put(child, ch);
}else{
//如果不存在,直接添加child属性
JSONArray ch = new JSONArray();
ch.add(aVal);
hashVP.put(child, ch);//之前少写了一句
/******************************疑问部分*******************************/
}
}else{
r.add(aVal);
}
}
return r;
}