对象创建语句放在循环外和循环内的区别

来源:互联网 发布:电脑软件论坛排行榜 编辑:程序博客网 时间:2024/06/04 19:34

每一个对象创建的时候都会有一个ID。List对象在执行add方法的时候是将对象的引用放入List中。上述代码中创建对象的语句如果放在外面,在将对象add到List中时,前后向List中add的对象都是同一个,所以放在外面的时候最后List中的对象是同一个对象。

    @Override    public List<EasyUITreeNode> getItemCatList(long parentId) {        TbItemCatExample example = new TbItemCatExample();        Criteria criteria = example.createCriteria();        criteria.andParentIdEqualTo(parentId);        List<TbItemCat> list = mapper.selectByExample(example);        List<EasyUITreeNode> resultList = new ArrayList<>();        for (TbItemCat itemCat: list) {            EasyUITreeNode node = new EasyUITreeNode();            node.setId(itemCat.getId());            node.setText(itemCat.getName());            node.setState(itemCat.getIsParent() ? "closed" : "open");            resultList.add(node);            for (int i = 0; i < resultList.size(); i++) {                System.out.println(resultList.get(i).getText()    }
阅读全文
0 0
原创粉丝点击