[英]different handles in public static final class variable
I have clas that emulates enum behavior for java 1.4 我有模拟Java 1.4枚举行为的类
public class PacketType {
String Name ="9";
public static final PacketType None = new PacketType("9");
public static final PacketType StartOfOperation = new PacketType("1");
PacketType (String Name ) {
this.Name = Name;
}
public String toString() {
return Name ;
}
public static void main(String[] args) {
PacketType p = PacketType.StartOfOperation;
if (p == PacketType.StartOfOperation) {
System.out.print("==");
}
if (p.equals(PacketType.StartOfOperation) ) {
System.out.print("equals");
}
}
}
Now I need to know which value has variable p
. 现在,我需要知道哪个值具有变量
p
。 Both , equals
and ==
pass checking in the main function. ,
equals
和==
通过了main函数中的检查。 But in case I have several threads in my application it does't pass this check. 但是,如果我的应用程序中有多个线程,则不会通过此检查。 I have assigned the same static variable
PacketType.StartOfOperation
for all my PacketType
variables. 我为所有
PacketType
变量分配了相同的静态变量PacketType.StartOfOperation
。 Debugger shows that I have the same value, but not the same variable handler (that is why it not pass equal
and ==
). 调试器显示我具有相同的值,但没有相同的变量处理程序(这就是为什么它不传递
equal
和==
)。 I expect that it should have the same handle. 我希望它应该具有相同的句柄。 Why it behaves so strange?
为什么它表现得如此奇怪?
When you use ==
it returns true if both references point to same object. 当使用
==
,如果两个引用都指向同一个对象,则返回true。
if (p == PacketType.StartOfOperation)
Here both the references points to different objects, hence it will not execute. 这里两个引用都指向不同的对象,因此将不会执行。 Try this
尝试这个
PacketType p =PacketType.None;
PacketType p1 =PacketType.None;
if (p == p1)
{
System.out.print("=="); //prints ==
}
Since None is static, every reference points to same object and ==
will return true. 由于None是静态的,因此每个引用都指向同一对象,并且
==
将返回true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.