Is there a way to detect if two objects in Java are aliased to each other? In C I guess we can check the memory addresses that two pointers are pointing to. But is there a way to do that in Java?
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)
Alias is used in Java when the reference of more than one is linked to the same object. The drawback of aliasing is when a user writes to a specific object, and the owner for some other references does not guess that object to change.
Use the ReferenceEquals method to determine whether two references refer to the same object. The concept of reference equality applies only to reference types. Value type objects cannot have reference equality because when an instance of a value type is assigned to a variable, a copy of the value is made.
In java, the variables are references so you can compare them using ==
to see if they refer to the same object.
Object a = ...
Object b = a;
boolean areSame = (a == b); //Will be true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With