简体   繁体   中英

Objects and Reference Count | Java

Consider the following code snippet in Java:

Customer obj1 = new  Customer();  
Customer obj2 = new Customer();  
Customer obj3 = obj2;  
obj3 = obj1;   

How many reference variables and objects are created here? The solutions I came across were all confusing. Please explain.

After

Obj3= Obj1;

You'll have two objects and 3 references. Obj1 and Obj3 will reference to the same object.

Customer Obj1= new  Customer();  

// Customer object is created on the heap and obj1 refers it

Customer Obj2= new Customer();  

//Customer object is created on the heap and obj2 refers it

Customer Obj3= Obj2;  

// obj3 will refer to customer object created by obj2

 Obj3= Obj1;   

// obj3 (previosly refering to cust obj craeted by obj2 will be lost) and will now refer to cust obj created by obj1

Thus i would say 2 objects and 3 ref variables

  • obj1 and obj3 refering to Object created by obj1
  • obj2 refers to Object created by obj2 itself

Although the JLS doesn't forbid it, AFAIK no JVM uses reference counting, it is just too unreliable. Note: C++ smart pointer uses references counts but these are very inefficient.

You have up to three references to two different objects.

Note: unless your code does something useful with them the JVM can optimise this code away to nothing, in which case you will have no references or objects.

假设custObj2new初始化,并从上面的片段初始化,其3个对象(包括custObj2 )和4个引用(包括Obj3

创建了三个变量和两个对象。

2 objects are created (the first 2 lines).

There are 3 reference variables created (Obj1, Obj2, and Obj3 are all reference variables.)

The last 2 lines simply assign references to 2 different objects to Obj3.

Step through it iteratively...

Customer Obj1= new  Customer();  

One new object created, referenced by Obj1

Customer Obj2= new Customer();  

A second object created, referenced by Obj2

Customer Obj3= custObj2;  

Obj3, a reference variable, refers to custObj2 (which doesn't exist in this set of data, we'll assume it was created earlier?)

Obj3= Obj1; 

Obj3 is re-assigned to point at Obj1.

In the end you have the three references, Obj1, Obj2, and Obj3 as well as 2 objects, (first two statements) and finally an ambiguous custObj2 ... if you meant to type Obj2 then ignore that part :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM