I have clas that emulates enum behavior for 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
. Both , equals
and ==
pass checking in the main function. 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. Debugger shows that I have the same value, but not the same variable handler (that is why it not pass equal
and ==
). 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.