我有以下递归方法,它返回嵌套集合中的元素数量。集合包含子集合和元素。 有没有更快的算法来实现这一点?
int elementCount = 0;
@Override
public int getElementCount(CollectionDTO collectionDTO){
if(collectionDTO == null){
return elementCount;
}
if (collectionDTO.getChildCollectionDTOs() != null
&& collectionDTO.getChildCollectionDTOs().size() > 0) {
for (CollectionDTO collection : collectionDTO.getChildCollectionDTOs())
getElementCount(collection);
}
if(collectionDTO.elements != null && collectionDTO.elements.size() > 0)
elementCount +=collectionDTO.elements.size();
return elementCount;
}
最佳答案
在最坏的情况下,您会调用collectionDTO.getChildCollectionDTOs()
三次,因此您应该考虑只调用一次,将结果存储在变量中并重用它。
如果该方法的另一个调用者对该对象具有相同的引用,则该类级别变量 elementCount
的使用将产生副作用,并且不会返回正确的结果。
您应该始终使用大括号 {}
,尽管它们对于单行 if
语句或 for
循环是可选的。这只会让你的代码更不容易出错。
应用这些要点将导致
@Override
public int getElementCount(CollectionDTO collectionDTO){
if(collectionDTO == null){
return 0;
}
int elementCount = 0;
if(collectionDTO.elements != null && collectionDTO.elements.size() > 0) {
elementCount +=collectionDTO.elements.size();
}
List<CollectionDTO> children = collectionDTO.getChildCollectionDTOs();
if (children == null){
return elementCount;
}
for (CollectionDTO collection : children)
elementCount += getElementCount(collection);
}
return elementCount;
}
关于java - 递归:查找元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33315268/