Hi,
I'm reading Head First
Java and just got through ch. 9 "Life and Death of an Object". After feeling confident with the material the final exercise has completely thrown me in a couple of ways. Please find the code below from the exercise (I added a print statement to understand what is happening to the ArrayList reference). I don't understand why the reference "aList" in main has additional elements added to it when it is sent to the methods in the other classes. I thought Pass-By-Value in Java meant that a copy of "aList" (or basically a copy of an ArrayList reference is sent to the constructor of the new class and the new class creates a local ArrayList (object) and assigns it to the local ArrayList reference variable and that this does not affect "aList" in main. Instead, both the aList in main and the individual local variables have the same elements. I thought "aList" here would have none, and each of the local ArrayList references would have only the values added to the local list of the respective class.
Also, the loop "for ( int z=0; z<20; z++ ) {RetentionBot ret = new RetentionBot(aList);}" doesn't make sense to me. Isn't this creating an object, assigning it to "ret", and in the next loop creating another object, assigning it to "ret" and abandoning the first one? What's the point of that? And why would the ArrayList keep the abandoned objects on its list? All are listed on "aList" after this loop runs. What's the point of that?
Up until now the book has been great but this one has thrown me. Thank you for your help!
import java.util.*;
public class TestLifeSupportSim
{
public static void main (
String[] args)
{
ArrayList aList = new ArrayList();
ArrayList bList = new ArrayList();
ArrayList cList = new ArrayList();
System.out.println(aList);
V2Radiator v2 = new V2Radiator(aList);
V3Radiator v3 = new V3Radiator(aList);
for ( int z=0; z<20; z++ ) {RetentionBot ret = new RetentionBot(aList);}
System.out.println("aList" + aList);
} // end main
} // end class
class V2Radiator
{
V2Radiator (ArrayList v2list )
{
for ( int x = 0; x < 5; x++ )
{
v2list.add(new SimUnit("V2Radiator"));
} // end for loop
} // end constructor
} // end class V2Radiator
class V3Radiator
{
V3Radiator ( ArrayList lglist )
{
System.out.println();
for ( int g = 0 ; g < 10; g++ )
{
lglist.add ( new SimUnit ("V3Radiator"));
} // end for loop
} // end constructor
} // end class V3Radiator
class RetentionBot
{
RetentionBot ( ArrayList rlist )
{
rlist.add(new SimUnit("Retention"));
} // end constructor
} // end class RetentionBot
class SimUnit
{
String botType;
SimUnit(String type)
{
botType = type;
} // end constructor
int powerUse()
{
if ("Retention".equals(botType)) {return 2;}
else{ return 4;}
} // end powerUse()
} // end class SimUnit