2016-11-06 77 views
-2
enum Expression { 

    Good("good"), 
    Bad("bad");  

    private String name; 
    Expression(String str) { 
     this.name = str; 
    } 

    public String getName(){ 
     return name; 
    } 
} 

如果還可以使用相同的'好'來表示幾個,即「好」,「非常好」,「好」,但所有這些變化可以通過相同的Expression.Good訪問?這聽起來很奇怪,但如果可能的話,它確實很有用。任何解決方法,如果不可能?枚舉元素可以在Java中使用多於1個值

如何在我的意圖中使用它?在這裏:

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! 
    } 
+1

[多值類型的Java枚舉(http://stackoverflow.com/questions/19600684/java-enum-with-multiple-value-types) – Dez

+1

你可以有你喜歡的任何參數的可能的複製。 – SLaks

+2

目前還不清楚你在這裏想要什麼,具有「好」**值的「Expression.Good」與「好」,「很好」或「好」**有什麼不同? –

回答

-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); 
    } 
} 
1

我會用可變參數:

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); 
    } 
} 

將在我看來,最乾淨的語法,你可以將可變參數陣列放入SetList,這裏有很大的靈活性。

if (Expression.POSITIVE.matches("Great")) { 
    //Great! 
} 
+0

@MickMnemonic考慮到'O(1)'的含義,我會考慮一個'HashSet'的最好情況。但這僅僅是爲了展示枚舉構造的可變參數。 – Rogue

+0

對不起,我沒有注意到你的'matches()'實現。是的,'Set'在這裏運行得很好。 –