1

What would be the most efficent to check if something is on a list of enums? I've looked around for a while and it wasn't very clear. Arrays don't have a contains() function and hashmaps are key:value.

Something like:

if(enumlist.contains(foo.enum())){
    // Do something
}
  • See also "Item 32: Use `EnumSet` instead of bit fields"—[Effective Java](http://java.sun.com/docs/books/effective/). – trashgod Aug 26 '11 at 02:01

2 Answers2

3

Use List#indexOf().

if (enumList.indexOf(foo) > -1) {
    // go crazy
}

Alternately, you can use the (extremely efficient) EnumSet data structure to store the objects — if you're okay with not being able to store duplicate elements.

if (enumSet.contains(foo)) {
    // just, like, whatever, man
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
2

EnumSet has a suitable contains() method.

Addendum: Using this example, the following prints true.

System.out.println(Resolution.deluxe.contains(Resolution.RES_256));
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045