简体   繁体   中英

checking if the enum exists

I have:

@AllArgsConstructor
public enum EnumTest {

    ENUM_TEST1(1),
    ENUM_TEST2(2),
    ENUM_TEST3(3),
    ENUM_TEST4(4),
    ENUM_TEST5(5),
    ENUM_TEST6(6),
    ENUM_TEST7(7),
    ENUM_TEST8(8),
    ENUM_TEST9(9),
    ENUM_TEST10(10);

    private int value;

}

I would like to check if a parameter is inside the enum, I can do this:

EnumUtils.isValidEnum(EnumTest.class,"ENUM_TEST6");

but what would be the correct way to compare only some enum for example, I have this:

Arrays.asList(ENUM_TEST6,ENUM_TEST7).contains(newParam.getEnumTest());

but asList uses a (new) so it would be correct to do something like this to improve performance a little or what is the best practice you can think of?

ENUM_TEST6.equals(newParam.getEnumTest()) || ENUM_TEST7.equals(newParam.getEnumTest());

Don't use Arrays.asList(ENUM_TEST6,ENUM_TEST7) , instead use EnumSet :

EnumSet.of(ENUM_TEST6, ENUM_TEST7)

If this is something re-usable, add it to the enum :

@AllArgsConstructor
public enum EnumTest {

    ENUM_TEST1(1),
    ENUM_TEST2(2),
    ENUM_TEST3(3),
    ENUM_TEST4(4),
    ENUM_TEST5(5),
    ENUM_TEST6(6),
    ENUM_TEST7(7),
    ENUM_TEST8(8),
    ENUM_TEST9(9),
    ENUM_TEST10(10);

    private int value;

    private static final EnumSet<EnumTest> TEST_6_7 = EnumSet.of(ENUM_TEST6, ENUM_TEST7);

    public static boolean is6or7(EnumTest value) {
        return TEST_6_7.contains(value);
    }
}

If the collection of valid enums is very large, you will want to go with the asList implementation, but create and store that list in an appropriate scope for reuse. If the collection of valid enums is small (2-5, say), use of a list (or other collection) is doing a lot of unnecessary work.

But, you would need to adjust the code, if getEnumTest answers a string, neither contains not equals will work. The collection would be of the names of the enums: ENUM_TEST6.name() .

Also, if the collection of valid enums is very large, a HashSet would be better, as List.contains in basic implementations (say, ArrayList ) will be slow for large collections.

Consider doing it this way. That's what EnumSets are for. They also include

  • EnumSet.complementOf
  • EnumSet.allOf
  • EnumSet.noneOf
    public static void main(String[] args) {
        method(EnumSet.of(EnumTest.ENUM_TEST1, EnumTest.ENUM_TEST2));

    }   
    public static void method(EnumSet<EnumTest> eset) {
        if (eset.containsAll(EnumSet.of(EnumTest.ENUM_TEST1,EnumTest.ENUM_TEST2))) {
            // do something.
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM