递归:查找元素数量

时间:2015-10-24 06:36:00

标签: java recursion

我有以下递归方法,它返回嵌套Collection中的元素数。集合包含子集合和元素。 是否有更快的算法来实现这一目标?

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;
}

1 个答案:

答案 0 :(得分:1)

在最糟糕的情况下,您要调用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;
}
相关问题