您的位置:首页 > 编程语言 > Java开发

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

2017-08-01 16:48 218 查看
每一个对象创建的时候都会有一个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()
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java