Java Reference
In-Depth Information
Discussion
Arrays can be used to hold any linear collection of data. The items in an array must all be of
the same type. You can make an array of any primitive type or any object type. For arrays of
primitive types , such as int s, boolean s, etc., the data is stored in the array. For arrays of ob-
jects , a reference is stored in the array, so the normal rules of reference variables and casting
apply. Note in particular that if the array is declared as Object[] , object references of any
type can be stored in it without casting, although a valid cast is required to take an Object
reference out and use it as its original type. I'll say a bit more on two-dimensional arrays in
Multidimensional Structures ; otherwise, you should treat this as a review example:
public
public class
Array1 {
@SuppressWarnings ( "unused" )
public
class Array1
public static
static void
void main ( String [] argv ) {
int
int [] monthLen1 ;
// declare a reference
monthLen1 = new
new int
int [ 12 ];
// construct it
int
int [] monthLen2 = new
int [ 12 ]; // short form
// even shorter is this initializer form:
int
new int
int [] monthLen3 = {
31 , 28 , 31 , 30 ,
31 , 30 , 31 , 31 ,
30 , 31 , 30 , 31 ,
};
final
final int
int MAX = 10 ;
Calendar [] days = new
new Calendar [ MAX ];
for
for ( int
int i = 0 ; i < MAX ; i ++) {
// Note that this actually stores GregorianCalendar
// etc. instances into a Calendar Array
days [ i ] = Calendar . getInstance ();
}
// Two-Dimensional Arrays
// Want a 10-by-24 array
int
int [][] me = new
new int
int [ 10 ][];
for
for ( int
int i = 0 ; i < 10 ; i ++)
me [ i ] = new
new int
int [ 24 ];
// Remember that an array has a ".length" attribute
System . out . println ( me . length );
System . out . println ( me [ 0 ]. length );
Search WWH ::




Custom Search