Seitaridis Seitaridis -4 years ago 141
Java Question

Serializable classes and the == operator

Here is the source code of the String.equals method:

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}


Since String is Serializable, does it make sense to use the == operator in the String.equals method? If we try to compare two different String objects, maybe with the same memory address, located on different VM, will this work correctly?

In my own code I use equals method to compare two strings. I know what == does. I am asking if it make sense to have a == comparison in the equals method of the String class.

Answer Source

Serializable means that an instance of the class can be converted into bytes and back into a an object instance using Java's default serialization mechanisms. When an object is deserialized, a new object instance is created based on the bytes and that instance exists in the JVM where it was deserialized. Serialization/deserialization does not magically make the same object instance accessible in multiple JVMs, but it just creates new object instances which are copies of each other.

Two JVMs cannot share object instances, so it's not possible that the == operator could be used to compare the addresses of object instances from different address spaces.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download