在Enum中使用开关

时间:2013-01-25 09:49:47

标签: java

如果我在switch中使用getByIntValue()该怎么办?是否真的有必要使用SparseArray

public enum Gender {
    Unknown(0),
    Male(1),
    Female(2);

    private static final SparseArray<Gender> lookupTable = new SparseArray<Gender>();
    static {
        for (final Gender gender : EnumSet.allOf(Gender.class)) {
            lookupTable.put(gender.intValue, gender);
        }
    }

    private final int intValue;

    public static Gender getByIntValue(int val) {
        return lookupTable.get(val);
    }

    private Gender(int intValue) {
        this.intValue = intValue;
    }

    public int getIntValue() {
        return intValue;
    }
}

3 个答案:

答案 0 :(得分:2)

如果您发布了真实的int值,则无需在每个枚举成员上明确设置它们,也不需要switch。只需使用

Gender.values()[intValue]

答案 1 :(得分:2)

由于你的int值从0变为2,没有空洞,你的确可以简单地使用数组。一个开关也可以,虽然它可能比数组查找稍慢。但除非你将这种方法称为数十亿次,否则它不会产生明显的差异。使用您认为最清楚,最容易理解和维护的内容。

答案 2 :(得分:0)

List.copyOf( EnumSet.allOf( Gender.class ) )

警告:除了最极端的情况之外,这种优化练习似乎很愚蠢,如mentioned by JB Nizet。对于实际工作,我可能会推荐Answer by Marko Topolnik中的解决方案。但是,为了好玩,我在这个球上挥了挥棒。

似乎目标是使用给定数字0,1,2来快速访问静态不可修改的集合。

As of Java 10,我们在“default”界面上使用了这些新的已实施(List)方法:List.of&amp; List.copyOf。这些产生了不可修改的集合。虽然支持实现没有记录并且可能会发生变化,但我认为它类似于具有类似性能的数组。如果支持实现检测到存在EnumSet并使用某种bit vector,则性能甚至可能比传统阵列更快。

我通过将List传递给List.copyOf( Collection )来填充EnumSet

所以,这个:

private static final SparseArray<Gender> lookupTable = new SparseArray<Gender>();
static {
    for (final Gender gender : EnumSet.allOf(Gender.class)) {
        lookupTable.put(gender.intValue, gender);
    }
}

......变成了这个:

private static final List < Gender > lookupTable = List.copyOf( EnumSet.allOf( Gender.class ) );

整个班级,main用于演示。

package com.basilbourque.example;

import java.util.EnumSet;
import java.util.List;

public enum Gender {
    UNKNOWN( 0 ),
    MALE( 1 ),
    FEMALE( 2 );

    private static final List < Gender > lookupTable = List.copyOf( EnumSet.allOf( Gender.class ) );

    private final int intValue;

    public static Gender getByIntValue ( int val ) {
        return lookupTable.get( val );
    }

    public int getIntValue () {
        return intValue;
    }

    // Constructor
    private Gender ( int intValue ) {
        this.intValue = intValue;
    }

    public static void main ( String[] args ) {
        // Testing.
        System.out.println( Gender.UNKNOWN.intValue );
        System.out.println( Gender.getByIntValue( 0 ) );
        System.out.println( "----" );
        System.out.println( Gender.MALE.intValue );
        System.out.println( Gender.getByIntValue( 1 ) );
        System.out.println( "----" );
        System.out.println( Gender.FEMALE.intValue );
        System.out.println( Gender.getByIntValue( 2 ) );
    }

}

跑步时。

  

0

     

UNKNOWN

           

1

     

MALE

           

2

     

FEMALE

顺便说一句,作为生物学默认值,FEMALE应该在MALE之前。