Reputation: 17
I know you can have something like
public enum letters{
A, B, C, D
}
then have something like with each letter having its own class with a method
switch(letters)
case A:
A.methodA();
break;
case B:
B.methodB();
break;
case C:
C.methodC();
break;
case D:
D.methodD();
break;
default:
System.out.println("Learn the alphabet");
but can you have something like
switch(listOfLetterEnums)
...
In my program I turn command line enum arguments into a list and I need to know how to run each of the enums' method from that list whether it be a switch statement or something else.
I should add when I try it I get an error saying "cannot convert List. Only convertible int values or enum variables" would converting to a list of enums work if the above is possib
Upvotes: 0
Views: 1414
Reputation: 3516
You will need to put a for loop around the switch statement to parse each element of the list separately. If the list is an Iterable then it should look something like this:
for (letterEnum : listOfLetterEnums) {
switch(letterEnum) {
...
}
}
For this to work, your list will need to implement the Iterator interface or extend a class which implements it. In this case you probably want to extend ArrayList.
If the list is an array you can just parse each element of the array:
for (int i = 0; i < listOfLetterEnums.length; i++) {
switch(listOfLetterEnums[i]) {
...
}
}
Upvotes: 2
Reputation: 1066
You need to loop over the list, and switch based on the value.
letters[] listOfLetterEnums = { letters.A, letters.B, letters.C, letters.D };
for(letter let : listOfLetterEnums)
{
switch(let)
{
case A:
A.methodA();
break;
case B:
B.methodB();
break;
case C:
C.methodC();
break;
case D:
D.methodD();
break;
default:
System.out.println("Learn the alphabet");
}
}
Upvotes: 0
Reputation: 5103
public class Test {
private enum Foo {
ABC, DEF;
}
public static void main(String... args) {
List<Foo> myfoos = new ArrayList<Foo>();
myfoos.add(Foo.ABC);
for(Foo i:myfoos)
switch (i) {
case ABC:
System.out.println("do abc");
break;
case DEF:
System.out.println("do def");
break;
}
}
}
Upvotes: 0