Can you break out of a switch case from within a loop?

78 views Asked by At

I have a list of objects that I don't want to contain duplicates. Since the objects are expensive to create, I don't want to use a set, as that requires an object to be created first, before determining if it is already present in the set. Instead, I want to check if the list already contains an object made from the same primitive data I'm currently processing. I also decide which specific object to create with a switch statement. So I wrote the following code:

List<ExpensiveObject> objects = new ArrayList<>();
List<PrimitiveData> input = readInput();

for(int data : input) {
    switch(data.Condition) {

        case Condition.FIRST:
            for(ExpensiveObject object : objects) {
                if(data.isAlreadyPresent(object))
                    break;
            }

            objects.add(new ExpensiveObject(data));
            break;
    
        case Condition.SECOND:
            // Some other code...
            break;
    
        // More Cases...
    
        default:
            break;
    }
}

Of course, what happens is that if the condition is true, the for loop is broken, not the switch statement. I know that I can easily work around this issue by introducing a boolean variable, but I would still like to know if there is a way to break the switch case in this way.

1

There are 1 answers

5
matt On BEST ANSWER

You can use a label.

myloop:
for(int i = 0; i<10; i++){
    for(int j = 0; j<10; j++){
        if(i<3 && j==5){
            break;
        }
        if(j == 6){
            break myloop;
        }
        System.out.println(i + ", " + j );
    }
}

When you run that, the break myloop ends the outter loop.

This works the same with a switch statement.

outter:
for(int i = 0; i<10; i++){
    switcher:
    switch(i){
        case 4:
            for(int j = 0; j<6; j++){
                break switcher;
            }
            System.out.println("didn't break");
        case 5:
            break outter;
        default:
            break;
    }
    System.out.println(i);
}

The default and case 4 both break the switch statement, but case 5 breaks to the outter loop.

Case 4 has a loop that gets broken to the switch statement, so it doesn't not print the extra println cmd. Which is similar to OPs objects.add(new ExpensiveObject(data));