list使用时内存溢出

今天解决了一个困扰很长的问题,遍历一个集合,取出值递归赋值给一个实体类,想要得到的报文如下:

[
    {
        "conditionList": [
            {
                "t_classroom": "classid",
                "t_student": "classid"
            },
            {
                "t_classroom": "classname",
                "t_student": "name"
            }
        ],
        "selectBlock": {
            "joinInfos": [
                {
                    "conditionList": [
                        {
                            "t_classroom": "gradeid",
                            "t_grade": "gradeid"
                        }
                    ],
                    "selectBlock": {
                        "joinInfos": [
                            {
                                "conditionList": [ { "t_grade": "gradeid", "t_nation": "gradeid" } ],
                                "selectBlock": { "table": "t_nation" } }
                        ],
                        "table": "t_grade"
                    }
                }
            ],
            "table": "t_classroom"
        }
    }
]

一个selectBlock中如果有关联表信息,就有joinInfos,递归往下….

在写代码的时候,把逻辑想明白了。

List joins = new ArrayList<>();
JoinInfo joinInfo = null;
SelectBlock block = null;
for (int i = list.size() - 1; i >= 0; i--) {
    block = new SelectBlock(tables.get(i), null, null, joins);
    joinInfo = new JoinInfo(null, list.get(i), block);
    joins.add(joinInfo);
}

joinInfos.add(joinInfo);

但是用ObjectMapper打出joinInfo的值报内存溢出的错。跟断点看了一下joins,竟然递归了很多个selectBlock。

list不用了就需要清除掉,所以改成下面的代码就好了:

List joins = null;
JoinInfo joinInfo = null;
SelectBlock block = null;
for (int i = list.size() - 1; i >= 0; i--) {
    block = new SelectBlock(tables.get(i), null, null, joins);
    joinInfo = new JoinInfo(null, list.get(i), block);

    joins = new ArrayList<>(); // 清空一下
    joins.add(joinInfo);
}

    joinInfos.add(joinInfo);

你可能感兴趣的:(工作笔记)