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.
You can use a label.
When you run that, the break myloop ends the outter loop.
This works the same with a switch statement.
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));