• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

How to writeObject an array?

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 80666
478
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic