enum Expression {
Good("good"),
Bad("bad");
private String name;
Expression(String str) {
this.name = str;
}
public String getName(){
return name;
}
}
如果有可能也使用相同的'Good'来表示更多,即“很好”,“非常好”,“很好”,但所有这些变化都可以通过相同的Expression.Good访问?这可能听起来很奇怪,但如果有可能,它实际上是有用的。如果不可能,任何解决方法?
如何在我的意图中使用它?这里:
String str = "great";
String str2 = "good";
然后我希望两者都是真的:
If(Expression.Good.getName().equals(str)) {
// I want it to be true!
}
If(Expression.Good.getName().equals(str2)) {
// I want it to be true too!
}
答案 0 :(得分:1)
我会使用varargs:
enum Expression {
POSITIVE("Good", "Great", "Awesome"),
NEGATIVE("Bad", "Get out"),
;
private final String[] words;
private Expression(String... words) {
this.words = words;
}
public String getRandomWord() {
return this.words[ThreadLocalRandom.current().nextInt(this.words.length)];
}
public boolean matches(String word) {
//can also use HashSet, and potentially consider matching against lowercase
return Arrays.stream(this.words).anyMatch(word);
}
}
在我看来,这将是最干净的语法,你可以将varargs数组放入Set
或List
,这里有很大的灵活性。
if (Expression.POSITIVE.matches("Great")) {
//Great!
}
答案 1 :(得分:-1)
public enum Expression {
GOOD(Arrays.asList("Good", "Great", "Wonderfull")),
BAD(Arrays.asList("Bad", "Terrible"));
private final List<String> name;
private Expression(final List<String> str) {
this.name = str;
}
//Will return a immutable list with all the names
public final List<String> getName(){
return name;
}
//Checks if the value has that name
public boolean hasName(String n) {
return name.contains(n);
}
}