Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if two objects are aliased in Java?

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?

like image 548
JRR Avatar asked Jul 09 '12 13:07

JRR


People also ask

How do you check if two objects are of the same type 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.

How can you tell if two objects are the same class?

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)

Does Java allow aliasing?

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.

Which of the following methods test if both references refer to same object in memory?

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.


1 Answers

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.
like image 142
Oleksi Avatar answered Oct 14 '22 00:10

Oleksi