gpt4 book ai didi

java - java中 "java.lang.Enum"类型对象的身份和状态是什么?

转载 作者:行者123 更新时间:2023-12-01 18:13:42 24 4
gpt4 key购买 nike

在下面的代码中,

class Example{}
Example ex1 = new Example();
Example ex2 = new Example();
bool compareAddress = (ex1 == ex2);

此处,compareAddress给出false,因为identityex1指向的对象的内存地址,并且ex2class Example{} 类型的对象内的字段值(如果有)定义该对象的状态

但是在下面的代码中,

enum Company{
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;

private Company(int value){
this.value = value;
}

}
Company x1 = Company.EBAY;
Company x1 = Company.EBAY;
bool compareValues = (x1 == x2);

此处,compareValues 给出 true

那么,x1x2指向的对象的身份和状态是什么?

最佳答案

An enum is a special type of class.

例如

enum Company {
EBAY
}

将编译为

final class Company extends Enum<Company> {
public final static Company EBAY = new Company(); // almost, this constructor invocation will have arguments
}

在 Java 进程的剩余生命周期中,EBAY 字段将保持相同的引用值,即对 Company 实例的引用。

来自JLS ,

Because there is only one instance of each enum constant, it is permitted to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

关于java - java中 "java.lang.Enum"类型对象的身份和状态是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31039649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com