2015-09-25 94 views
0
class Enum{ 
    enum Season { WINTER, SPRING, SUMMER, FALL } 
    public static void main(String[] args) { 

     System.out.println(new Enum().pf()); 
     } 

    String pf() { 
     if (Season.WINTER.equals("WINTER")) return "equal"; 
     else return "not equal"; 
    } 
} 

爲什麼結果不相等。那是因爲Season.WINTER是一個對象,而不是一個String?我不確定?當我們可以得到「平等」的結果?Java枚舉等於

+0

想想那樣:你會期待''「WINTER」.equals(Season.WINTER)'返回'true'嗎? – Holger

回答

3

您正在比較枚舉類型與String,它將返回false

您可以在您的枚舉類型上調用name()以將其與String進行比較。

否則,您可以使用switch聲明。

也見枚舉實施equals(來源從Oracle的Java 8):

/** 
* Returns true if the specified object is equal to this 
* enum constant. 
* 
* @param other the object to be compared for equality with this object. 
* @return true if the specified object is equal to this 
*   enum constant. 
*/ 
public final boolean equals(Object other) { 
    return this==other; 
} 

正如你看到的例子,對於enum S上的實現是一樣的Object,即它只比較參考。