0

Suppose I have an enum structure like the following

public enum MyItems {
    pc("macbook"),
    phone("nokia"),
    food("sandwich"),
    animal("dog");

    private String item;
    MyStuff(String stf) {
        item = stf;
    }
    public String identify() {
        return item;
    }
}

Now, suppose I want to find out what "type" an item I own is. For instance, in the case of "macbook", this would yield pc. Similarly, "sandwich" would represent a food item.

I have the following for-loop for checking if a String belongs to an enum:

String currentItem;    //Some arbitrary string, such as "macbook"/"nokia", etc.
for(MyStuff stuff : MyStuff.values()) {
    if(stuff.identify().equals(currentItem)) {
        //PRINT OUT:
        //currentItem + " is a " + pc/phone/food/animal
    }
}

That is, how can I go from taking the parameter of an enum value, to the enum value "type" it represents.

This is the desired output:

currentItem = "nokia"
>>>> nokia is a [phone]
yulai
  • 741
  • 3
  • 20
  • 36

3 Answers3

2

You could add a revese lookup method to your enum:

public enum MyItems {
...

    public static MyItems resolve(String name) {
        for (MyItems item : values()) {
            if (item.identify().equals(name)) {
                return item;
            }
        }
        return null;
    }
}

Usage:

String currentItem = "nokia";
MyItems item = MyItems.resolve(currentItem);
System.out.println(currentItem + " is a [" + item + "]");
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • Thanks, however when doing this, I still get "nokia is a [nokia]", instead of "nokia is a [phone]". – yulai Sep 15 '15 at 19:09
  • An enum's toString() method returns the enum constant's name per default (here: "phone"). Have you, by any chance, overridden the toString() method in your specific enum? – Peter Walser Sep 15 '15 at 20:32
1

To get your print statement you want with the current code you have, just use:

String currentItem = "nokia";    //Some arbitrary string, such as "macbook"/"nokia", etc.
for(MyStuff stuff : MyStuff.values()) {
    if(stuff.identify().equals(currentItem)) {
        System.out.println(currentItem + " is a " + stuff);
    }
}

EDIT: With that being said, you should probably move this into MyStuff as Peter suggested.

Evan LaHurd
  • 977
  • 2
  • 14
  • 27
0

You can use enums in switch statements, which makes them both very fast and easy to read.

for (MyStuff thing : getStuff()) {
switch (thing): {
case phone: //something
case pc:  //something else
default: //none
}
mvd
  • 2,596
  • 2
  • 33
  • 47