从字符串中获取枚举的索引? [英] Get index of enum from string?

查看:178
本文介绍了从字符串中获取枚举的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串值,我也有一个字符串数组和一个包含该范围的枚举。
要获取数组中字符串的索引,请从提供的值中写出:

I have a string value, I also have an array of strings and an enum containing the range also. To get the index of the string in the array, from the value supplied I write this:

Arrays.asList(myClass.BAUD_RATES).indexOf(username)

如何为枚举执行此操作?我可以使用序数吗?或者我必须自己制作方法吗?

How do I do this for an enum? Can I use ordinal? Or do i have to make my own method?

方法可能如下:

public enum Fruit {
   ...
   static public boolean isMember(String aName) {
       Fruit[] aFruits = Fruit.values();
       for (Fruit aFruit : aFruits)
           if (aFruit.fruitname.equals(aName))
               return aFruit;
       return false;
   }
   ...
}


推荐答案

不确定我是否理解正确,但也许你正在寻找

Not sure if I understand you correctly but maybe you are looking for

YourEnum.valueOf("VALUE").ordinal();




  • YourEnum.valueOf(VALUE) 返回名称为 VALUE

  • 的枚举值,每个枚举值知道其位置(从零开始索引)我们可以看到使用 ordinal()方法。

    • YourEnum.valueOf("VALUE") returns enum value with name VALUE
    • and each enum value knows its position (indexed from zero) which we can see using ordinal() method.
    • 这篇关于从字符串中获取枚举的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆