Java
arrays
An array is simply a sequence of either
objects or primitives, all the same
type and packaged together under one
identifier name. Arrays are defined
and used with the square-brackets
indexing operator [ ]. To define an
array you simply follow your type
name with empty square brackets:
int[] a1;
You can also put the square brackets
after the identifier to produce exactly
the same meaning:
int a1[];
This conforms to expectations from
C and C++ programmers. The former
style, however, is probably a more
sensible syntax, since it says that
the type is “ an int array.”
The compiler doesn’t allow you to
tell it how big the array is. This
brings us back to that issue of “
handles.” All that you have at this
point is a handle to an array, and
there’s been no space allocated for
the array. To create storage for the
array you must write an initialization
expression. For arrays, initialization
can appear anywhere in your code,
but you can also use a special kind
of initialization expression that
must occur at the point where the
array is created. This special initialization
is a set of values surrounded by curly
braces. The storage allocation (the
equivalent of using new) is taken
care of by the compiler in this case.For
example:
int[] a1 = { 1, 2, 3, 4, 5
};
|
|
|
|
|