java枚举字符串吗,Java:检查枚举是否包含给定的字符串?

博客探讨了在Java中寻找类似ArrayList.contains()方法的枚举实现。作者提出了一个解决方案,即通过遍历枚举值并比较名称来检查枚举是否包含特定值。如果枚举非常大,建议使用HashSet以提高查找效率。
摘要由CSDN通过智能技术生成

Here's my problem...I'm looking for (if it even exists) the enum equivalent of ArrayList.contains();.

Here's a sample of my code problem:

enum choices {a1, a2, b1, b2};

if(choices.???(a1)}{

//do this

}

Now, I realize that an ArrayList of Strings would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.

Assuming something like this doesn't exist, how could I go about doing it?

Thanks!

解决方案

This should do it:

public static boolean contains(String test) {

for (Choice c : Choice.values()) {

if (c.name().equals(test)) {

return true;

}

}

return false;

}

This way means you do not have to worry about adding additional enum values later, they are all checked.

Edit: If the enum is very large you could stick the values in a HashSet:

public static HashSet getEnums() {

HashSet values = new HashSet();

for (Choice c : Choice.values()) {

values.add(c.name());

}

return values;

}

Then you can just do: values.contains("your string") which returns true or false.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值