2015-09-25 95 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,即它只比较参考。