有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

枚举和字符串之间的java映射?

所以,我最近读了this post,我想有效地做同样的事情

我真的不在乎“丑”,所以我实施了以下方法之一:

public enum Day {

    Monday(1), 
    Tuesday(2), 
    Wednesday(3), 
    Thursday(4), 
    Friday(5), 
    Saturday(6), 
    Sunday(7);

    public final int id;

    Day(int id) {
        this.id = id;
    }

    public static Day getByID(int id) {
        Day d = null;
        for (Day dTemp : Day.values())
        {
            if (id == dTemp)
            {
                d = dTemp;
                break;
            }
        }

        return d;
    }

    public Day getNext() {
        return values()[(ordinal()+1)%values().length];
    }

    public Day getPrev() {
        return values()[(ordinal()-1)%values().length];
    }
}

但是,当我这样做时,它的问题在于if语句:

if (id == dTemp)

它说它们是不兼容的类型。我该怎么做才能修好它


共 (2) 个答案

  1. # 1 楼答案

    if(id == dTemp.id)
    

    应该有用


    或者尝试使用enumordinal()方法

    public final int ordinal()Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.

    Returns: the ordinal of this enumeration constant. See.


    我复制了你的代码并进行了相应的测试

    两者都有

    if (id == dTemp.ordinal()+1)
    

    if(id == dTemp.id)
    

    工作正常,生产如期。声明

    System.out.println(Day.Friday.getByID(1));
    

    制作周一

  2. # 2 楼答案

    使用if ( id == dTemp.id )。枚举是类,枚举值是对象而不是int,因此不能(显式或隐式)强制转换到int

    或者,请注意,枚举有一个序号,即其位置的id。在您的示例中,Monday将有序号0,Sunday将有序号6。您可以通过调用ordinal()方法来访问序号

    因此,如果id是一个基础,那么您可以执行以下操作:

    public static Day getByID(int id) {   
      //check id is between 1 and 7, I'll leave that for you
      return Day.values()[id - 1];
    }
    

    请注意,您可能希望在私有静态变量中缓存Day.values(),然后访问缓存的数组

    顺便问一下,你在问题中提到的字符串在哪里