Java 中 Enum 数据类型的 equals 和 == 运算符
我们用四个常量定义了 Devices 枚举。
enum Devices { LAPTOP, MOBILE, TABLET, DESKTOP; }
我们创建了几个对象并用常量为它们赋值。
让我们使用 equals() 和 == 来比较它们。首先,从 equals() 开始 −
if(d1.equals(d2)) System.out.println("Devices are the same."); else System.out.println("Devices are different.");
现在,让我们继续操作并检查 ==
if(d1 == d3) System.out.println("Devices are the same."); else System.out.println("Devices are different.");
以下是同時說明 equals() 和 == 运算符的最終範例 −
範例
public class Demo { enum Devices { LAPTOP, MOBILE, TABLET, DESKTOP; } public static void main(String[] args) { Devices d1, d2, d3, d4; d1 = Devices.LAPTOP; d2 = Devices.LAPTOP; d3 = Devices.TABLET; d4 = Devices.DESKTOP; if(d1.equals(d2)) System.out.println("Devices are the same."); else System.out.println("Devices are different."); if(d1 == d3) System.out.println("Devices are the same."); else System.out.println("Devices are different."); } }
輸出
Devices are the same. Devices are different.
广告