How do I break out of nested loops in Java?

前端 未结 30 3562
梦毁少年i
梦毁少年i 2020-11-21 11:51

I\'ve got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do somethin         


        
30条回答
  •  天命终不由人
    2020-11-21 12:04

    Usually in such cases, it is coming in scope of more meaningful logic, let's say some searching or manipulating over some of the iterated 'for'-objects in question, so I usually use the functional approach:

    public Object searching(Object[] types) { // Or manipulating
        List typesReferences = new ArrayList();
        List typesReferences2 = new ArrayList();
    
        for (Object type : typesReferences) {
            Object o = getByCriterion(typesReferences2, type);
            if(o != null) return o;
        }
        return null;
    }
    
    private Object getByCriterion(List typesReferences2, Object criterion) {
        for (Object typeReference : typesReferences2) {
            if(typeReference.equals(criterion)) {
                 // here comes other complex or specific logic || typeReference.equals(new Object())
                 return typeReference;
            }
        }
        return null;
    }
    
    
    

    Major cons:

    • roughly twice more lines
    • more consumption of computing cycles, meaning it is slower from algorithmic point-of-view
    • more typing work

    The pros:

    • the higher ratio to separation of concerns because of functional granularity
    • the higher ratio of re-usability and control of searching/manipulating logic without
    • the methods are not long, thus they are more compact and easier to comprehend
    • higher ratio of readability

    So it is just handling the case via a different approach.

    Basically a question to the author of this question: what do you consider of this approach?

    提交回复
    热议问题