Re: help
On Sat, 01 Mar 2008 20:33:47 -0800, wee <rbulseco@gmail.com> wrote:
i'm confused with the way java initializes object arrays:
if i declare array objects as such;
JTextField[] arr_field;
arr_field[0] = new JTextField(10);
arr_field[1] = new JTextField(10);
the compiler reports it as an error, but if i declare it as such;
JTextField[] arr_field = {new JTextField(10), new JTextField(10);
then the complier compiles it. shouldn't they be the same?
No, they're not the same. In the latter example, you're providing an =
initial value for the array and its elements. In the former, the variab=
le =
is never initialized, and so referencing any elements in the array is =
illegal.
and also,
why can't i initialize array objects as;
JTextField arr_field[3];
for (int i = 0; i < 3; i++) {
arr_field[i] = new JTextField(10);
}
Well, you can't use that syntax. But you could write this:
JTextField[] arr_field = new JTextField[3];
for (int i = 0; i < arr_field.length(); i++)
{
arr_field[i] = new JTextField(10);
}
In other words, you can allocate a new array, assign that instance to th=
e =
variable, and then access the array through that variable. (You'll note=
I =
also changed the loop termination...I prefer not hard-coding numbers whe=
n =
not necessary, as it makes the code more reliable and flexible).
See http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.htm=
l =
for more details.
Pete