So what I am trying to do in JAVA is take in a set of values and then compare those values against the same category of values in an Enum so I can find a specific enum.
In other words I have a bunch of Enums
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
}
Now I have an array of strings
String[] myStringArray = {"Blue", "Oblong", "Berry"};
String[] myStringArrayTwo = {"Red", "Round", "Fruit"};
how could I compare my String Arrays to the String values in the enums so I can figure out which enum Constant my String Array Represents.
In Reality I have a class that reads in these string values from a file into an array and then I want to assign an enum to the class so I can give it a predefined classification that can be used by other classes.
(note: the constructor needs not be private
-- it is by default for enums)
You could code a method in the enum such as:
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;
}
Then you would:
final Fruits f = Fruits.findByCharacteristics(theArray);
// check whether f is null; if not, you have a match
However, imho, the code "smells"; you should try a different approach. One such "smell" is that the method above requires an array with at least three elements.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加