现在的位置: 首页 > 综合 > 正文

JAVA Array Tutorial(1)

2014年02月03日 ⁄ 综合 ⁄ 共 1974字 ⁄ 字号 评论关闭

An array is a named list of data items that all have the same type. You declare an array variable in the same way you declare any simple variable, but you insert a pair of square rackets after the type. After
you create an array variable, you still need to reserve memory space. You use the same procedure to create an array that you use to create an object. Recall that when you create a class named Employee, you can declare an Employee object with a declaration
such as : Employee oneWorker;

However, that declaration does not actually create the oneWorker object. You create the oneWorker object when you sue the keyword new and the constructor method, as in: oneWorker =  new Employee(); Similarly,
declaring an array and reserving memory space for it are two distinct processes. To reserve memory locations for 20 sale objects, you declare the array variable with the following statement: double[] sale;

Then you create the array with the following statement:

Sale = new double[20];

Just as with objects, you can declare and create an array in one statement with the following:

Double[] sale =  new double[20];

In java, the size of an array is never declared immediately following the array name.

The statement double[] size = new double[20]; reserves 20 memory locations for 20 sale values.

A variable that has a primitive type, such as int, holds a value. A variable with a reference type, such as an array, holds a memory address where a value is stored. Aarray names represent computer memory
addresses.

When you use the keyword new to define an array, the array name acquires an actual memory address value. For example, when you define someNums in the following statement, a memory address is assigned: int[]
someNums = new int[10]; When you declare int[] someNums = new int[10]; each elemet of someNums has a value of 0 because someNums is a numeric array. Wwhen you create an array of objects, each reference is assigned the value null.

In Java, you cannot directly initialize part of an array. For example, you cannot create an array of 10 elements and initialize only five; you either must initialize every element or none of them.

For(int val:scoreArray){

     System.out.println(val);

}

To display data for seven Employees stored in the emp array, you can write the following:

For(Employee worker: emp){

      System.out.println(worker.getEmpNum());

}

抱歉!评论已关闭.