Adding an enumeration type to a list

If I need to add an enum attribute to a list, how do I declare a list? Let's say an enumeration class:

public enum Country{ USA, CANADA; } 

I want to make:

 List<String> l = new ArrayList<>(); l.add(Country.USA); 

What should be used instead of List<String>?

+4
source share
3 answers

If you want the string type to use this:

l.add(Country.USA.name());

otherwise the answer is MByD

+4
source

Must be:

 List<Country> l = new ArrayList<Country>(); l.add(Country.USA); // That one for you Code Monkey :) 
+10
source

If you want to keep any listing, use this:

 List<? extends Enum<?>> list = new ArrayList<Country>(); Enum<?> someEnumValue = list.get(0); // Elements can be assigned to Enum<?> System.out.println(someEnumValue.name()); // You can now access enum methods 
+2
source

All Articles