Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to writeObject an array?

 
M Marsden
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Posts: 51450
87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic