Можете ли вы выйти из случая переключателя изнутри цикла? ⇐ JAVA
-
Anonymous
Можете ли вы выйти из случая переключателя изнутри цикла?
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 objects = new ArrayList(); List 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.
Источник: https://stackoverflow.com/questions/781 ... hin-a-loop
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 objects = new ArrayList(); List 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.
Источник: https://stackoverflow.com/questions/781 ... hin-a-loop
Мобильная версия