简体   繁体   中英

How do I load into an array all the elements in one variable of an enum?

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"

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM