物件導向程式設計

 

 

    3.7 陣列

 

 


授課教師:陳慶瀚

WWW : http://www.miat.ee.isu.edu.tw/java

E-mail : pierre@isu.edu.tw   

 


3.7.1 宣告一個陣列

Like all other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. One array cannot store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:

int[] k;
float[] yt;
String[] names;

This says that k is an array of ints, yt is an array of floats and names is an array of Strings. In other words you declare an array like you declare any other variable except that you append brackets to the end of the type.

You also have the option to append the brackets to the variable instead of the type.

int k[];
float yt[];
String names[];

The choice is primarily one of personal preference. You can even use both at the same time like this

int[] k[];
float[] yt[];
String[] names[];

 

配置陣列記憶體

Declaring arrays merely says what kind of values the array will hold. It does not create them. Java arrays are objects, and like any other object you use the new keyword to create them. When you create an array, you must tell the compiler how many components will be stored in it. Here's how you'd create the variables declared on the previous page:

k = new int[3];
yt = new float[7];
names = new String[50];

The numbers in the brackets specify the length of the array; that is, how many slots it has to hold values. With the lengths above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. This step is sometimes called allocating the array since it sets aside the memory the array requires.

 

3.7.2 陣列的初值化

 

Individual components of an array are referenced by the array name and by an integer which represents their position in the array. The numbers you use to identify them are called subscripts or indexes into the array.

Subscripts are consecutive integers beginning with 0. Thus the array k above has components k[0], k[1], and k[2]. Since you start counting at zero there is no k[3], and trying to access it will throw an ArrayIndexOutOfBoundsException. You can use array components wherever you'd use a similarly typed variable that wasn't part of an array. For example this is how you'd store values in the arrays above:

 

k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[17] = 7.5f;
names[4] = "Fred";

This step is called initializing the array or, more precisely, initializing the components of the array. Sometimes the phrase "initializing the array" is used to mean when you initialize all the components of the array.

For even medium sized arrays, it's unwieldy to specify each component individually. It is often helpful to use for loops to initialize the array. Here is a loop which fills an array with the squares of the numbers from 0 to 100.

float[] squares;
squares = new float[101];

for (int i=0; i <= 100; i++) 
{
   squares[i] = i*i;
}

Two things you should note about this code fragment:

  1.  

    Watch the fenceposts! Since array subscripts begin at zero you need 101 components if you want to include the square of 100.

  2.  

    Although i is an int, it is promoted to a float when it is stored in squares, since squares is declared to be an array of floats

課堂練習:

1. 使用一維陣列存放使用者由main(String args[])傳入的字串引數,陣列大小為args.length,每個字串引數分別放在args[0],args[1],......,最後再將陣列輸出至螢幕 。(範例程式)

2.    使用一維陣列存放10個使用者輸入的整數值,計算其平均值並輸出。(範例程式)


 3.7.3 二維陣列的宣告

 

So far all these arrays have been one-dimensional. That is, a single number could locate any value in the array. However sometimes data is naturally represented by more than one number. For instance a position on the earth requires a latitude and a longitude.

The most common kind of multidimensional array is the two-dimensional array. If you think of a one-dimensional array as a column of values, you can think of a two-dimensional array as a table of values like this

 

 

c0

c1

c2

c3

r0

0

1

2

3

r1

1

2

3

4

r2

2

3

4

5

r3  

3

4

5

6

r4  

4

5

6

7

Here we have an array with five rows and four columns. It has twenty total elements. However we say it has dimension five by four, not dimension twenty. This array is not the same as a four by five array like this one:

 

 

c0

c1

c2

c3

c4

r0

0

1

2

3

4

r1

1

2

3

4

5

r2

2

3

4

5

6

r3

3

4

5

6

7

We need to use two numbers to identify a position in a two-dimensional array. These are the element's row and column positions. For instance if the above array is called J then J[0][0] is 0, J[0][1] is 1, J[0][2] is 2, J[0][3] is 3, J[1][0] is 1, and so on.

Here's how the elements in a four by five array called M are referred to:

 

M[0][0]

M[0][1]

M[0][2]

M[0][3]

M[0][4]

M[1][0]

M[1][1]

M[1][2]

M[1][3]

M[1][4]

M[2][0]

M[2][1]

M[2][2]

M[2][3]

M[2][4]

M[3][0]

M[3][1]

M[3][2]

M[3][3]

M[3][4]

 

3.7.4 二維陣列的配置和初值化

 

Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However you have to specify two dimensions rather than one, and you typically use two nested for loops to fill the array.

This example fills a Two-Dimensional Array with the sum of the row and column indexes

 

class FillArray 
{

  public static void main (String args[]) 
  {
  
    int[][] M;
    M = new int[4][5];
  
    for (int row=0; row < 4; row++) 
    {
      for (int col=0; col < 5; col++) 
      {
        M[row][col] = row+col;
      }
    }
    
  }
  
}

Of course the algorithm you use to fill the array depends completely on the use to which the array is to be put. Program 9.3 calculates the identity matrix for a given dimension. The identity matrix of dimension N is a square matrix which contains ones along the diagonal and zeros in all other positions.

 

class IDMatrix 
{

  public static void main (String args[]) 
  {
  
    double[][] ID;
    ID = new double[4][4];
  
    for (int row=0; row < 4; row++) 
    {
      for (int col=0; col < 4; col++) 
      {
        if (row != col)ID[row][col]=0.0;
        else ID[row][col] = 1.0;
      }
    }
    
  }
  
}

In two-dimensional arrays ArrayIndexOutOfBoundsExceptions occur whenever you exceed the maximum column index or row index.

You can also declare, allocate, and initialize a a two-dimensional array at the same time by providing a list of the initial values inside nested brackets. For instance the three by three identity matrix could be set up like this:

double[][] ID3 = 
{
  {1.0, 0.0 , 0.0},
  {0.0, 1.0, 0.0},
  {0.0, 0.0, 1.0}
};

The spacing and the line breaks used above are purely for the programmer. The compiler doesn't care. The following works equally well:

 

double[][] ID3 = {{1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{0.0, 0.0, 1.0}};

課堂練習:

3. 使用9x9的二維陣列存放九九乘法表並輸出至螢幕

4.    設計一個3x3矩陣相加的程式,輸入兩個矩陣值,輸出矩陣相加結果。

5.    設計一個3x3矩陣相乘的程式,輸入兩個矩陣值,輸出矩陣相乘結果。

3.7.5 多維陣列的宣告、配置和初值化

You don't have to stop with two dimensional arrays. Java permits arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you're probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.

The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. The program below declares, allocates and initializes a three-dimensional array. The array is filled with the sum of its indexes.

 

class Fill3DArray 
{

  public static void main (String args[]) 
  {
  
    int[][][] M;
    M = new int[4][5][3];
  
    for (int row=0; row < 4; row++) 
    {
      for (int col=0; col < 5; col++) 
      {
        for (int ver=0; ver < 3; ver++) 
        {
          M[row][col][ver] = row+col+ver;
        }
      }
    }
  }
}

You need the additional nested for loop to handle the extra dimension. The syntax for still higher dimensions is similar. Just add another pair of brackets and another dimension.

課堂練習:

6. 使用二維float陣列來建立一個10(rows)x3(columns)的資料表M,第一個column存放[0,10]之間的亂數值,第二個column存放 第一個column的平方值,第三個column存放 第一個column的開根號值。

提示:

A. 使用Math.random( )產生介於0到1的亂數值,例

    doublw r = Math.random( );

B. 開根號的函式為和Math.sqrt(double )

7. 擴充練習6的程式,再產生一個3(rows)x3(columns)的二維float陣列T。第一個row的三個column分別存放M的三個column所有值當中的最大值,第二個row的三個column分別存放M的三個column所有值當中的最小值,第三個row的三個column分別存放M的三個column的平均值。



 

物件導向程式設計

義守大學電機系 陳慶瀚

2001.10.22