Reputation: 25
I'm trying to get the elements of one enum variable into an array using a method in another class (I hope I'm explaining that right, please look at the code)
I've tried all kinds of things, for loops, with and without constructors.
public enum coffeetypes {
COFFEE1 ("AMERICANO", "LATTE", "CAPPUCCINO"),
COFFEE2 ("ESPRESSO", "RISTRETTO", "AMERICANO"), ;
}
I want to get the result
"AMERICANO", "LATTE", "CAPPUCCINO"
or "ESPRESSO", "RISTRETTO", "AMERICANO"
not "AMERICANO" "ESPRESSO"
Upvotes: 1
Views: 53
Reputation: 1772
If you have a field for each property.
import java.util.Arrays;
import java.util.List;
class Coffee {
public static void main(String[] args) {
System.out.println(CoffeeTypes.COFFEE1.getAttributes());
}
public enum CoffeeTypes {
COFFEE1 ("AMERICANO", "LATTE", "CAPPUCCINO"),
COFFEE2 ("ESPRESSO", "RISTRETTO", "AMERICANO");
private String n1;
private String n2;
private String n3;
CoffeeTypes(String n1, String n2, String n3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;
}
public List<String> getAttributes() {
return Arrays.asList(n1, n2, n3);
}
}
}
Output
[AMERICANO, LATTE, CAPPUCCINO]
Upvotes: 1
Reputation: 4465
Your enum type doesn't even compile as it is missing a constructor and a private field. When adding this, it is easy to add a getElements() method so you can access the list from outside your enum:
import java.util.Arrays;
public class Coffee {
public enum CoffeeTypes {
COFFEE1("AMERICANO", "LATTE", "CAPPUCCINO"),
COFFEE2("ESPRESSO", "RISTRETTO", "AMERICANO");
String[] elements;
private CoffeeTypes(String... elements)
{
this.elements=elements;
}
public String[] getElements()
{
return elements;
}
}
public static void main(String[] args) {
CoffeeTypes myinstance=CoffeeTypes.COFFEE1;
System.out.println(Arrays.asList(myinstance.getElements()));
}
}
Arrays.asList is just used to print the array in a readable way.
Upvotes: 1