从蜇获取枚举的指数? [英] Get index of enum from sting?

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

问题描述

我有一个字符串值,我也有一个数组或字符串和包含的范围也是一个枚举。
为了得到字符串的索引数组中,从所提供的数值我写这篇文章:

  Arrays.asList(myClass.BAUD_RATES).i​​ndexOf(用户名)

我要如何枚举做到这一点?我可以使用顺序?还是我必须做我自己的方法?

该方法可能会去这样的:

 公共枚举水果{
   ...
   静态公共布尔isMember(字符串aName){
       水果[] = aFruits Fruit.values​​();
       对于(水果aFruit:aFruits)
           如果(aFruit.fruitname.equals(aName))
               返回aFruit;
       返回false;
   }
   ...
}


解决方案

不知道如果我理解正确,但也许你正在寻找

  YourEnum.valueOf(值)序();


  • YourEnum.valueOf(值)返回名称枚举值

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

I have a string value, I also have an array or 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?

The method might go like:

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") 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天全站免登陆