Five Arrays of Java

Source: Internet
Author: User

One-dimensional arrays

Q Declaration and definition of a one-dimensional array

Application of the one-dimensional array of q

Declaration and definition of a one-dimensional array

A one-dimensional array (one-dimensional array) is essentially the same type of variable list. To create an array, you must first define the type required for the array variable. The declaration format for a common one-dimensional array is:

Typevar-name[];

Where type defines the base type of the array. The base type determines the data type of each of the basic elements that make up the array. In this way, the base type of the array determines the data type stored by the array. For example, the following example defines an array with the data type int, named Month_days.

int month_days[];

Although the example defines the fact that month_days is an array variable, there is actually no array variable present. In fact, the value of month_days is set to NULL, which represents an array with no values. To make the array month_days an actual, physically existing array of integers, you must assign the address to it using the operator new and assign it to month_days. operator new is an operator that is dedicated to allocating memory. You'll learn more about operator New in later chapters, but you now need to use it to allocate memory for arrays. When operator new is applied to a one-dimensional array, its general form is as follows:

Array-var = new Type[size];

Where type specifies the data type being assigned, size specifies the number of variables in the array, and Array-var is the array variable that is linked to the array. That is, using operator new to assign an array, you must specify the type of array elements and the number of elements. When an array is allocated with operator new, the elements in the array are automatically initialized to zero. The following example assigns an array of 12 integer elements and links them to arrays month_days.

Month_days = new INT[12];

With the execution of this statement, the array month_days will point to 12 integers, and all elements in the array will be initialized to zero.

Let's review the process above: It takes 2 steps to get an array. In the first step, you must define the type required for the variable. In the second step, you must use operator new to allocate memory for the data to be stored for the array, and assign them to the arrays variable. This allows the arrays in Java to be dynamically allocated. If the concept of dynamic allocation is unfamiliar to you, don't worry, it will be discussed in detail later in this book.

Once you have assigned an array, you can specify its subscript within square brackets to access specific elements in the array. All array subscripts start with zero. For example, the following statement assigns a value of 28 to the second element of the array month_days.

MONTH_DAYS[1] = 28;

The following program displays the values stored in the array element labeled 3.

System.out.println (Month_days [3]);

In summary, the following program-defined array stores the number of days per month.

Demonstrate aone-dimensional array.
Class Array {
publicstatic void Main (String args[]) {
int month_days[];
Month_days = new INT[12];
Month_days[0] = 31;
MONTH_DAYS[1] = 28;
Month_days[2] = 31;
MONTH_DAYS[3] = 30;
Month_days[4] = 31;
MONTH_DAYS[5] = 30;
Month_days[6] = 31;
MONTH_DAYS[7] = 31;
MONTH_DAYS[8] = 30;
MONTH_DAYS[9] = 31;
MONTH_DAYS[10] = 30;
MONTH_DAYS[11] = 31;
System.out.println ("April has" +month_days[3] + "days.");
}
}

When you run this program, it prints out the number of days in April. As mentioned earlier, the Java array subscript starts from zero, so the number of days in the April array element is month_days[3] or 30. It is possible to combine the declaration of an array variable with the allocation of the array itself, as follows:

int month_days[] = new INT[12];

This will be the professional practice of writing Java programs that you usually see. An array can be initialized at the time of declaration. This process is the same as the process of initializing a simple type. The initialization of an array (array initializer) is the list of expressions that are included in the curly braces separated by commas. The comma separates the values of the array elements. Java automatically allocates a large enough space to hold the number of initialization elements you specify without using operator new. For example, to store the number of days in a month, the following program defines an initialized array of integers:

An improved version of the previous program.

Class Autoarray {
public static void Main (String args[]) {
Intmonth_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
System.out.println ("Aprilhas" + month_days[3] + "days.");
}
}

When you run this program, you will see that it is the same as the output generated by the previous program.

Java is strictly checked to ensure that you do not accidentally store or reference values outside the range of the array. Java's runtime checks to make sure that all array subscripts are within the correct range (in this respect, Java differs fundamentally from C + +, which does not provide run boundary checking). For example, the running system checks each of the underlying values of the array month_days to ensure that it is included between 0 and 11. If you attempt to access elements outside the bounds of the array (negative numbers or larger than the array bounds), you will cause a run error.

Application of one-dimensional array

The following example uses a one-dimensional array to calculate the average of a set of numbers.

Average an array of values.

Class Average {

public static void Main (String args[]) {

Double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};

Double result = 0;

int i;

for (i=0; i<5; i++)

result = result + Nums[i];

System.out.println ("Average is" + RESULT/5);

}

}


Multidimensional arrays

Declaration and definition of multidimensional arrays

In Java, a multidimensional array (multidimensionalarrays) is actually an array of arrays. You may expect that these arrays are as formal and action-like as the general multidimensional arrays. However, you will see that there are some subtle differences. Define a multidimensional array variable to place each dimension in their respective brackets. For example, the following statement defines a two-dimensional array variable named TWOD.

int twod[][] = new INT[4][5];

The statement assigns an array of 4 rows and 5 columns and assigns it to the array Twod. In fact, this matrix represents the process by which an array of type int is implemented. Conceptually, this array can be represented in Figure 3-1.

The following programs assign values from left to right, from top to bottom, for each element of an array, and then display the values of the arrays:

Figure 3.1 Conceptual representation of a two-dimensional array (4 rows and 5 columns)

Demonstrate a two-dimensional array.

Class Twodarray {

public static void Main (String args[]) {

int twod[][]= new INT[4][5];

int I, j, k = 0;

for (i=0; i<4; i++)

for (j=0; j<5; J + +) {

TWOD[I][J] = k;

k++;

}

for (i=0; i<4; i++) {

for (j=0; j<5; j + +)

System.out.print (Twod[i][j] + "");

System.out.println ();

}

}

}

The results of the program run are as follows:

0 1 2) 3 4

5 6 7) 8 9

10 11 12) 13 14

15 16 17) 18 19

When you allocate memory to a multidimensional array, you only need to specify the first (leftmost) dimension of memory. You can allocate memory separately to the remaining dimensions. For example, the following program allocates memory to its first dimension when the array twod is defined, and the second dimension manually assigns the address.

int twod[][] = new int[4][];

Twod[0] = new INT[5];

TWOD[1] = new INT[5];

TWOD[2] = new INT[5];

TWOD[3] = new INT[5];

Application of multidimensional arrays

Although there is no merit in allocating memory separately to the second dimension in this case, it is different in other cases.

For example, when you manually allocate memory, you do not need to allocate memory for the same number of elements per dimension. As previously mentioned, since multidimensional arrays are actually arrays of arrays, the dimensions of each array are under your control. For example, the following program defines a two-dimensional array whose second dimension is unequal in size.

Manually allocate differingsize second dimensions.

Class Twodagain {

public static void Main (stringargs[]) {

int twod[][] = new int[4][];

Twod[0] = new INT[1];

TWOD[1] = new INT[2];

TWOD[2] = new INT[3];

TWOD[3] = new INT[4];

int I, j, k = 0;

for (i=0; i<4; i++)

for (j=0; j<i+1; J + +) {

TWOD[I][J] = k;

k++;

}

for (i=0; i<4; i++) {

for (j=0; j<i+1; j + +)

System.out.print (Twod[i][j] + "");

System.out.println ();

}

}

}

The output generated by the program is as follows:

0

1 2

3 4 5

6 7 8 9

The program-defined array can be represented as follows:

For most applications, we do not recommend the use of irregular multidimensional arrays because they run contrary to what people expect. However, irregular multidimensional arrays are used more efficiently in some cases. For example, if you need a large two-dimensional array that is only sparsely occupied (that is, the elements of one dimension are not all used), then an irregular array can be a perfect solution.

It is possible to initialize a multidimensional array. Initializing a multidimensional array is simply to enclose the initialization list of each dimension with its own curly braces. The following program produces a matrix in which each element of the matrix includes an array of subscript rows and columns of the product. Also note that in the initialization of an array you can use expressions as literal literals.

Initialize atwo-dimensional Array.

Class Matrix {

public static void Main (stringargs[]) {

Double m[][] = {

{0*0, 1*0, 2*0, 3*0},

{0*1, 1*1, 2*1, 3*1},

{0*2, 1*2, 2*2, 3*2},

{0*3, 1*3, 2*3, 3*3}

};

int I, J;

for (i=0; i<4; i++) {

for (j=0; j<4; j + +)

System.out.print (M[i][j] + "");

System.out.println ();

}

}

}

When you run this program, you will get the following output:

0.0 0.0 0.0 0.0

0.0 1.0 2.0 3.0

0.0 2.0 4.0 6.0

0.0 3.0 6.0 9.0

As you can see, each row in the array is initialized as specified by the initialization table.

Let's look at one more example of using multidimensional arrays. The following program first produces a 3x4x5 3-dimensional array, then loads each element generated with its subscript, and finally shows the array.

Demonstrate athree-dimensional array.

Class Threedmatrix {

public static void Main (stringargs[]) {

int threed[][][] = newint[3][4][5];

int I, j, K;

for (i=0; i<3; i++)

for (j=0; j<4; j + +)

for (k=0; k<5; k++)

THREED[I][J][K] = i * j * k;

for (i=0; i<3; i++) {

for (j=0; j<4; J + +) {

for (k=0; k<5; k++)

System.out.print (threed[i][j][k]+ "");

System.out.println ();

}

System.out.println ();

}

}

}

The output of the program is as follows:

0 0 0) 0 0

0 0 0) 0 0

0 0 0) 0 0

0 0 0) 0 0

0 0 0) 0 0

0 1 2) 3 4

0 2 4) 6 8

0 3 6) 9 12

0 0 0) 0 0

0 2 4) 6 8

0 4 8) 12 16

0 6 12) 18 24



Practical questions:

1. Thinking about real life, have we dealt with the concept of a set of identical types of data?

2. If you have learned the concept of a mathematical matrix, how does it relate to multidimensional arrays?



Summary:

In this chapter, we have mainly studied:

u array declaration, definition, use;

U one-dimensional array and multidimensional array application;



English vocabulary:

English Full text Chinese

Array Array Arrays



Practice Items:

There are now two boxes, one in which only eggs can be placed. You can only put tomatoes in the other box. There were 8 eggs and 12 tomatoes in two cases. Using object-oriented programming idea, and combining the concept of array to realize the initialization of the box and the procedure of adding eggs and tomatoes to the box;



Five Arrays of Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.