Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Array

Java Array

Arrays are one of the important data structures for every programming language, and of course different languages implement and handle arrays differently.

The arrays provided in the Java language are used to store a fixed number of elements of the same type.

You can declare an array variable, such as numbers[100], instead of declaring 100 separate variables number0, number1, ..., number99.

This tutorial will introduce the declaration, creation, and initialization of Java arrays, and provide the corresponding code.


Declaring Array Variables

You must first declare an array variable before you can use an array in a program. The syntax for declaring an array variable is as follows:

dataType

[

]

arrayRefVar

;

//

Preferred method

or

dataType

arrayRefVar

[

]

;

//

Same effect, but not the preferred method

** Note:** It is recommended to use dataType[] arrayRefVar the declaration style to declare array variables. The dataType arrayRefVar[] style comes from the C/C++ language and is adopted in Java so that C/C++ programmers can quickly understand the Java language.

Example

Below are code examples of these two syntaxes:

double

[

]

myList

;

//

Preferred method

or

double

myList

[

]

;

//

Same effect, but not the preferred method


Creating an Array

The Java language uses the new operator to create an array, as follows:


arrayRefVar = new dataType[arraySize];

The syntax statement above does two things:

The declaration of an array variable and the creation of an array can be done in a single statement, as shown below:


dataType[] arrayRefVar = new dataType[arraySize];

In addition, you can also create an array in the following way.


dataType[] arrayRefVar = {value0, value1, ..., valuek};

Array elements are accessed by index. The array index starts at 0, so the index value ranges from 0 to arrayRefVar.length-1.

Example

The following statement first declares an array variable myList, then creates an array containing 10 elements of type double, and assigns its reference to the myList variable.

TestArray.java File Code:

public

class

TestArray

{

public

static

void

main

(

String

[

]

args

)

{

//

Array Size

int

size

=

10

;

//

Defining an array

double

[

]

myList

=

new

double

[

size

]

;

myList

[

0

]

=

5

.6

;

myList

[

1

]

=

4

.5

;

myList

[

2

]

=

3

.3

;

myList

[

3

]

=

13

.2

;

myList

[

4

]

=

4

.0

;

myList

[

5

]

=

34

.33

;

myList

[

6

]

=

34

.0

;

myList

[

7

]

=

45

.45

;

myList

[

8

]

=

99

.993

;

myList

[

9

]

=

11123

;

//

Calculating the sum of all elements

double

total

=

0

;

for

(

int

i

=

0

;

i

<

size

;

i

++

)

{

total

+=

myList

[

i

]

;

}

System

.

out

.

println

(

"

The sum is:

"

total

)

;

}

}

The output of the above example is:


总和为: 11367.373

The image below depicts the array myList. Here the myList array has 10 double elements with indices from 0 to 9.

Java array structure illustration


Processing Arrays

Since the element type and size of an array are both fixed, when processing array elements we usually use a basic loop or a For-Each loop.

Example

This example completely demonstrates how to create, initialize, and manipulate an array:

TestArray.java File Code:

public

class

TestArray

{

public

static

void

main

(

String

[

]

args

)

{

double

[

]

myList

=

{

1

.9

,

2

.9

,

3

.4

,

3

.5

}

;

//

Printing all array elements

for

(

int

i

=

0

;

i

<

myList

.

length

;

i

++

)

{

System

.

out

.

println

(

myList

[

i

]

"

"

)

;

}

//

Calculating the sum of all elements

double

total

=

0

;

for

(

int

i

=

0

;

i

<

myList

.

length

;

i

++

)

{

total

+=

myList

[

i

]

;

}

System

.

out

.

println

(

"

Total is

"

total

)

;

//

Finding the largest element

double

max

=

myList

[

0

]

;

for

(

int

i

=

1

;

i

<

myList

.

length

;

i

++

)

{

if

(

myList

[

i

]

max

)

max

=

myList

[

i

]

;

}

System

.

out

.

println

(

"

Max is

"

max

)

;

}

}

The compilation and execution results of the above example are as follows:


1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

For-Each Loop

JDK 1.5 introduced a new loop type called the For-Each loop or enhanced loop, which can traverse an array without using an index.

The syntax format is as follows:

for(type element: array)
{
    System.out.println(element);
}

Example

This example is used to display all elements in the array myList:

TestArray.java File Code:

public

class

TestArray

{

public

static

void

main

(

String

[

]

args

)

{

double

[

]

myList

=

{

1

.9

,

2

.9

,

3

.4

,

3

.5

}

;

//

Printing all array elements

for

(

double

element

:

myList

)

{

System

.

out

.

println

(

element

)

;

}

}

}

The compilation and execution results of the above example are as follows:


1.9
2.9
3.4
3.5

Array as a Parameter of a Method

An array can be passed as a parameter to a method.

For example, the following is a method that prints the elements in an int array:

public

static

void

printArray

(

int

[

]

array

)

{

for

(

int

i

=

0

;

i

<

array

.

length

;

i

++

)

{

System

.

out

.

print

(

array

[

i

]

"

"

)

;

}

}

The example below calls the printArray method to print 3, 1, 2, 6, 4, and 2:

printArray

(

new

int

[

]

{

3

,

1

,

2

,

6

,

4

,

2

}

)

;


Array as the Return Value of a Method

public

static

int

[

]

reverse

(

int

[

]

list

)

{

int

[

]

result

=

new

int

[

list

.

length

]

;

for

(

int

i

=

0

,

j

=

result

.

length

1

;

i

<

list

.

length

;

i

++,

j

--

)

{

result

[

j

]

=

list

[

i

]

;

}

return

result

;

}

In the example above, the result array is the return value of the method.


Multidimensional Arrays

A multidimensional array can be regarded as an array of arrays; for example, a two-dimensional array is a special one-dimensional array whose every element is a one-dimensional array, for example:

String

[

]

[

]

str

=

new

String

[

3

]

[

4

]

;

Dynamic Initialization of Multidimensional Arrays (using a two-dimensional array as an example)

  1. Allocate space for each dimension directly, in the following format:

type

[

]

[

]

typeName

=

new

type

[

typeLength1

]

[

typeLength2

]

;

type can be a primitive data type or a composite data type; typeLength1 and typeLength2 must be positive integers, where typeLength1 is the number of rows and typeLength2 is the number of columns.

For example:

int

[

]

[

]

a

=

new

int

[

2

]

[

3

]

;

Analysis:

The two-dimensional array a can be viewed as an array with two rows and three columns.

  1. Starting from the highest dimension, allocate space for each dimension separately, for example:

String

[

]

[

]

s

=

new

String

[

2

]

[

]

;

s

[

0

]

=

new

String

[

2

]

;

s

[

1

]

=

new

String

[

3

]

;

s

[

0

]

[

0

]

=

new

String

(

"

Good

"

)

;

s

[

0

]

[

1

]

=

new

String

(

"

Luck

"

)

;

s

[

1

]

[

0

]

=

new

String

(

"

to

"

)

;

s

[

1

]

[

1

]

=

new

String

(

"

you

"

)

;

s

[

1

]

[

2

]

=

new

String

(

"

!

"

)

;

Analysis:

s[0]=new String[2] and s[1]=new String[3] This allocates reference space for the highest dimension, that is, limits the maximum length of data it can hold for the highest dimension, and then allocates space individually for each of its array elements s0=new String("Good") and other operations.

Referencing Multidimensional Arrays (using a two-dimensional array as an example)

For each element in a two-dimensional array, the reference method is arrayName[index1][index2], for example:

num

[

1

]

[

0

]

;


Arrays Class

The java.util.Arrays class can conveniently operate on arrays; all the methods it provides are static.

It has the following functions:

For details, please see the table below:

No. Method and Description
1 public static int binarySearch(Object[] a, Object key)
Searches the given array for the given value object (Byte, Int, double, etc.) using the binary search algorithm. The array must be sorted before the call. If the search value is contained in the array, returns the index of the search key; otherwise returns (-(insertion point) - 1).
2 public static boolean equals(long[] a, long[] a2)
If the two specified long-type arrays areEquality, then return true. If the two arrays contain the same number of elements and all corresponding element pairs in the two arrays are equal, the two arrays are considered equal. In other words, if the two arrays contain the same elements in the same order, the two arrays are equal. The same method applies to all other primitive data types (Byte, short, Int, etc.).
3 public static void fill(int[] a, int val)
Assigns the specified int value to each element in a specified range of the specified int-type array. The same method applies to all other primitive data types (Byte, short, Int, etc.).
4 public static void sort(Object[] a)
Sorts the specified object array into ascending order according to the natural ordering of its elements. The same method applies to all other primitive data types (Byte, short, Int, etc.).

Exercise

Java Array Quiz