[英]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?但是 asList 使用 (new) 所以做这样的事情来提高性能是正确的,或者你能想到的最佳实践是什么?
ENUM_TEST6.equals(newParam.getEnumTest()) || ENUM_TEST7.equals(newParam.getEnumTest());
Don't use Arrays.asList(ENUM_TEST6,ENUM_TEST7)
, instead use EnumSet
:不要使用
Arrays.asList(ENUM_TEST6,ENUM_TEST7)
,而是使用EnumSet
:
EnumSet.of(ENUM_TEST6, ENUM_TEST7)
If this is something re-usable, add it to the enum
:如果这是可重用的,请将其添加到
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.如果有效枚举的集合非常大,您将希望使用
asList
实现 go,但创建该列表并将其存储在适当的 scope 中以供重用。 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.如果有效枚举的集合很小(例如 2-5),则使用列表(或其他集合)会做很多不必要的工作。
But, you would need to adjust the code, if getEnumTest
answers a string, neither contains
not equals
will work.但是,您需要调整代码,如果
getEnumTest
回答一个字符串,则既不contains
也不equals
将起作用。 The collection would be of the names of the enums: ENUM_TEST6.name()
.该集合将是枚举的名称:
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.此外,如果有效枚举的集合非常大,则
HashSet
会更好,因为基本实现中的List.contains
(例如ArrayList
)对于大型 collections 会很慢。
Consider doing it this way.考虑这样做。 That's what
EnumSets
are for.这就是
EnumSets
的用途。 They also include它们还包括
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.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.