I was asked by my text to count the references to an object. Inside the given code was the following:
Honey honeypot = new Honey();
Honey [ ] ha = {honeypot, honeypot, honeypot, honeypot};
Bees b1 = new Bees();
b1.beeHA = ha;
where the constructor for Bees creates the Honey[ ] beeHA array.
Now I thought that beeHA would now hold the reference honeypot in four positions as does array ha and that these would be four separate references plus the four from the ha array making eight references. But the diagram the book gives as an answer say that the beeHA array only points to the ha array not to the object referenced by the honeypot reference variable making only four references. Am I thinking about this correctly?
If array ha were to be garbage collected (subject of the chapter) wouldn’t b1.beeHA[x] still contain the honeypot reference variable?
haisn’t an array – it’s a variable. The value of the variable is a reference to the array – as is the value ofb1.beeHA. So it doesn’t really make sense to talk about “arrayha” being garbage collected. When you write:that simply copies the value of
haintob1.beeHA. It’s not copying the array – it’s just copying the reference.The code you’ve shown creates one array containing four references to one instance of
Honey. There are two references to that array – one in the variablehaand one in the variableb1.beeHA.