所以我要在JAVA中尝试做的是获取一组值,然后将这些值与Enum中相同类别的值进行比较,以便找到一个特定的枚举。
换句话说,我有一堆枚举
public enum Fruits{
APPLE("Red", "Round", "Fruit", true),
//about 20 or so more Constants
ORANGE("Orange","Sphere","Citrus", true);
private String color;
private String shape;
private String category;
private boolean edible;
private Fruits(String color, String shape, String category, boolean edible){
this.color = color;
this.shape = shape;
this.category = category;
this.edible = edible;
}
//getter methods for each variable
}
现在我有一个字符串数组
String[] myStringArray = {"Blue", "Oblong", "Berry"};
String[] myStringArrayTwo = {"Red", "Round", "Fruit"};
我如何将我的字符串数组与枚举中的字符串值进行比较,以便可以找出我的字符串数组代表的常量。
在Reality中,我有一个类,将这些字符串值从文件中读取到数组中,然后我想给该类分配一个枚举,以便为它提供可以供其他类使用的预定义分类。
(注意:构造函数不必是private
-缺省情况下是枚举)
您可以在枚举中编写一个方法,例如:
public static findByCharacteristics(final String[] characteristics)
{
for (final Fruits candidate: values())
if (candidate.color.equals(characteristics[0])
&& candidate.shape.equals(characteristics[1])
&& candidate.category.equals(characteristics[2]))
return candidate:
return null;
}
然后,您将:
final Fruits f = Fruits.findByCharacteristics(theArray);
// check whether f is null; if not, you have a match
但是,恕我直言,代码“闻起来”;您应该尝试其他方法。这种“气味”之一是上述方法需要一个至少包含三个元素的数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句