簡體   English   中英

Java枚舉等於

[英]Java Enum equals

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? 我不確定? 而什么時候我們可以獲得“平等”的結果呢?

您正在將枚舉類型與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的實現與Object的實現相同,即,它僅比較引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM