list.remove 的陷阱

list  的数据结构是数组结构,并且物理存储结构是连续存储,在删除的时候,如果是

使用for 循环方式,会出现删除报错,或者,删除时,由于list 删除一个索引对象后,后面的索引会复制到前面,这时候循环删除的时候就乱了,

List调用remove(index)方法后,会移除index位置上的元素,index之后的元素就全部依次左移,即索引依次-1要保证能操作所有的数据,需要把index-1,否则原来索引为index+1的元素就无法遍历到(因为原来索引为index+1的数据,在执行移除操作后,索引变成index了,如果没有index-1的操作,就不会遍历到该元素,而是遍历该元素的下一个元素)。
 

这时候需要使用迭代器的遍历方式

@Override
	public ResponseObject getSourceClasslinkage() {
		List<Node> nodeList = sourceTableClassMapper.getSourceClassTreeData();
		HashMap<String, Node> map = new HashMap<String,Node>();
		
		for (Node node : nodeList) {
			map.put(node.getId(), node);
		}
		//list转成树
		List<Node> listtotree = TreeNode.listtotree(nodeList,map);
		Iterator<Node> it = listtotree.iterator();
	     while(it.hasNext()){
	    	 Node node = it.next();
	    	 List<Node> children = node.getChildren();
				if(CollectionUtils.isEmpty(children)){
					it.remove();
				}
	     }
		
		return ResponseObject.success(listtotree);
	}

Iterator.remove() 方法会在删除当前迭代对象的同时,会保留原来元素的索引。

猜你喜欢

转载自blog.csdn.net/yss1019/article/details/88578853