This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to writeObject an array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to writeObject an array?" Watch "How to writeObject an array?" New topic
Author

How to writeObject an array?

M Marsden
Greenhorn

Joined: Jun 18, 2008
Posts: 18
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?
Justin Fox
Ranch Hand

Joined: Jan 24, 2006
Posts: 802
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


You down with OOP? Yeah you know me!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37902
    
  22
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to writeObject an array?
 
Similar Threads
Head Start java Beatbox serialization/deserializatoin
Using JFileChooser instead of serialization hard coded files
HF BeatBoxFinal and MusicServer
Problems with serialization / deserialization.
another head first beatbox question