Forums Register Login

How to writeObject an array?

+Pie Number of slices to send: Send
Okay, this question is based on the following code (from p. 463 of Sierra & Bates, Head First Java)

public class MySendListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = new boolean[256];
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}
}
try {
FileOutputStream fileStream = new FileOutputStream(new File("Checkbox.ser"));
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(checkboxState);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
//end of code block

My question is based on the line:

os.writeObject(checkboxState);

Given that checkboxState is an array, shouldn't this be:

os.writeObject(checkboxState[]);

If not, why not?
+Pie Number of slices to send: Send
the compiler knows that the object checkedstates is an array...
hence the declaration "boolean [] checkedstates = new boolean[somenum]"

You only include the 'type' in the declaration if you are either creating an object or listing parameters for a function (there probably are other cases).

But thats the BASIC reason.

Justin Fox
+Pie Number of slices to send: Send
You sure, Justin?

All variables have to be declared with a type; in the case of checkboxState the type is boolean[], ie an array of booleans.

When you pass an argument to the writeObject() method, it takes Object as the type of argument--well, an array (of anything) is an object in its own right, so it can be called type Object.
But the name of the array is checkboxState, without the [], so that is what you write. Its type might have [] in, but its name doesn't have [] in.
Is that a spider in your hair? Here, threaten it with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2571 times.
Similar Threads
another head first beatbox question
Problems with serialization / deserialization.
Using JFileChooser instead of serialization hard coded files
HF BeatBoxFinal and MusicServer
Head Start java Beatbox serialization/deserializatoin
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 06:29:31.