Mike Wright

Greenhorn
+ Follow
since Feb 24, 2006
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Mike Wright

Thanks for the help. I keep forgetting things like String and ArrayList are objects.
16 years ago
Hello,

This forum was recommended in Head First Java so I thought I'd give it a shot. I was trying to do the 5 minute mystery at the end of the Garbage Collection chapter and I am confused. I am hoping someone can help me to better understand.

The puzzle revolves around a program which is creating too many of one type of object due to the way the constructors are written. I understand how the number of objects created is reached. My problem is I don't understand how the objects are surviving to be counted in the end. To me it seems they should be destroyed right after they are made. Below is the code:

import java.util.*;
class V2Radiator {
V2Radiator(ArrayList list) {
for(int x = 0; x < 5; x++) {
list.add(new SimUnit("V2Radiator"));
}
}
}

class V3Radiator extends V2Radiator {
V3Radiator(ArrayList lglist) {
super(lglist);
for(int g = 0; g < 5; g++) {
lglist.add(new SimUnit("V3Radiator"));
}
}
}

class RetentionBot {
RetentionBot(ArrayList rlist) {
rlist.add(new SimUnit("Retention"));
}
}

public class TestLifeSupportSim {
public static void main(String[] args) {
ArrayList aList = new ArrayList();
V2Radiator v2 = new V2Radiator(aList);
V3Radiator v3 = new V3Radiator(aList);
for(int z = 0; z < 20; z++) {
RetentionBot ret = new RetentionBot(aList);
}
}
}

class SimUnit {
String botType;
SimUnit(String type) {
botType = type;
}

int powerUse() {
if("Retention".equals(botType)) {
return 2;
}
else {
return 4;
}
}
}

The way I am looking at this is a copy of the ArrayList aList from Main is passed to the ArrayList list parameter in the constructor for an object like V2Radiator. The ArrayList list has 5 SimUnit objects added to it. The constructor ends its run and here is where I am confused.

If I understand correctly there is no connection between ArrayList list and aList because it was a copy of aList that was passed. Therefore, aList in main should not have any SimUnit objects, only list does. There is no instance variable for V2Radiator and list is a local variable of the constructor method. Shouldn't list then be blown off the stack once the constructor is done running? Wouldn't there need to be an instance variable of type ArrayList that is updated by the constructor in order for the ArrayList of SimUnit objects to survive?

I hope the above was understandable. Any insight anyone can provide is greatly appreciated.

Thanks,
Mike Wright
16 years ago