“Zero foundation Java development” fifth chapter array

Fifth chapter array

An array is a basic data structure that is used to store a set of elements of the same type. Arrays are useful, such as collections of classes offered by ArrayList, Java, HashMap, etc., based on arrays.

An array is a container used to store data. Once you define the type of the array element, you can only store this type of element inside the array. It’s important to remember that the elements in the array are indexed from 0.

In this chapter, we introduce arrays in Java, which include:

Array creation and initialization,
array elements, access to the common operations of
, multidimensional arrays, etc..

5.1 array declaration

There are two kinds of declarative syntax formats for one-dimensional arrays

Type varName[]; / / (1)


Type[] varName; / / (2)

The Type type here can be either a base type or an arbitrary reference type.
we usually use section (2) because it separates the type from the variable name and makes the semantics clearer.

For example, we declare a int array variable containing 10 digits

Int[] numbers;

However, we just can’t use the numbers variable just for the above statement.

screen snapshot 2017-08-19 11.52.42.png

In Java, you need to initialize the declared array variables to do related operations.

Java> int[] numbers = null; int[] numbers = null

The null here is the default value for the reference type. This null value is a very special value in Java, which we will discuss later in the chapter. The above code stores information about the numbers array variables in the stack memory. We can use the following diagram to represent it

declares array variable numbers

The type information of the array is already stored in the numbers variable at this point.

Java> numbers, instanceof, Object, java.lang.Boolean, res2 = false

The declaration of the array object above is actually the same as the object declaration of the generic class

Java> class Person{} Created Person java> Person P = null; java.lang.Object P = null java> P, instanceof, Person, java.lang.Boolean, res12 = false = type

5.2 creation and initialization of array object instances

The array is actually an object in Java, and the array instance is also created using the new operator. Only the declaration syntax of the array is quite special. It uses the type of the element plus the bracket Type[] varName, whereas the generic type declaration only needs to use Type varName.

5.2.1 array object creation

We use the new keyword to create an instance of the array object. Format as:

The array element type [] array name = new array element type [length];

This new process creates memory space for our array in heap space. Where length is the capacity size of an array. An array is a fixed length data structure that, once declared, does not change the length of this array in the life cycle of the array. If we want to dynamically expand, we need to copy the array to achieve. ArrayList dynamic expansion is the use of the Arrays.copyOf method. The Arrays.copyOf method also uses System.arraycopy, the native local method. We will introduce in the following section. Interested students can also read the code for the java.util.ArrayList class.

An array is a very fast data structure. If you already know the length of an element, you should use arrays rather than ArrayList.

Such as:

Java> numbers = new, int[10], int[], numbers = [0, 0, 0, 0, 0, 0,, 0, 0, 0, 0]

The process is illustrated below

creates an array object instance

Since an array is a reference type, its elements are equivalent to the class’s member variables, so after the array allocates space, each element is implicitly initialized in accordance with the rules of the member variables. For example, an integer array element without initialization defaults to 0, and the uninitialized Boolean value is false, and the String object array is null.

Java> boolean[], barray = new, boolean[2], boolean[], barray = [false, false]

The built-in property of the array length specifies the array length

Java> numbers.length, java.lang.Integer, res13 = 10, java> barray.length, java.lang.Integer, res17 = 2

Initialization of the 5.2.2 array

We can either initialize an array when we create an array, or we can initialize it later.

If we want to initialize the element while creating the array, use the following method

Java> int[], numbers = new, int[]{0,1,2,3,4,5,6,7,8,9}, int[], numbers = [0, 1, 2, 3, 4, 5,, 6, 7, 8, 9]

We can also save new int[] and use curly braces directly

Java> int[], numbers = {0,1,2,3,4,5,6,7,8,9}, int[], numbers = [0, 1, 2, 3, 4, 5,, 6, 7, 8, 9]

This very simple form is called Literals literal (Array).

It should be noted that if we use an uninitialized array object, the null pointer exception will result

Java> int[] x = null; int[] x = null java> x[0] java.lang.NullPointerException

We can also separate array definitions as well as allocating memory space operations and assignment operations, for example:

Java> String[] s = new String[3]; java.lang.String[] s = [null, null, null], java> s[0] = "ABC"; java.lang.String res23 = "ABC" java> s[1]= "XYZ"; java.lang.String res24 = "XYZ" java> s[2]= "OPQ"; java.lang.String res25 = "OPQ" java> s java.lang.String[] = "s" ABC "," XYZ "," OPQ "]

Typically, we use the for loop to initialize elements of an array, such as:

Java> int[] numbers = new int[10]; int[] numbers = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] java> for (int; I = 0; I 10; < i++) {numbers[i] = I * I java> numbers int[];}; numbers = 1, [0. 4, 9, 16, 25, 36, 49, 64, 81]

5.3 access to array elements

We use array index (subscript) to access elements of an array. Also, it is worth noting that the bounds check of arrays in Java, if the program accesses invalid array indexes, Java throws the ArrayIndexOutOfBoundException exception. for example

Java> String[] s = new String[3]; java.lang.String[] s = [null, null, null] java> s[-1] java.lang.ArrayIndexOutOfBoundsException: -1 java> s[3] java> s[4]; java.lang.ArrayIndexOutOfBoundsException: 3; java.lang.ArrayIndexOutOfBoundsException: 4

We can see that the negative index is invalid in Java and will throw ArrayIndexOutOfBoundException. An exception is thrown if we access the array element with an invalid index larger than the length of the array.

Index of 5.3.1 array

Java’s array claim starts at 0, [0] returns the first element, and [length-1] returns the last element. The code example is as follows

Java> int[], x = {1,2,3,4,5}, int[] = [1, 2, 3, 4, 5], java>, x[0], java.lang.Integer, res26 = 1, java>, x[x.length-1], java.lang.Integer, res27 = 5, X

As you can see, the index index of an array can be an integer constant or an integer expression.

Note that only when the declaration defines an array, and the operator new is allocated space or the array reference variable to an array of object space, can access (Reference) of each element in the array.

It is important to note that the length here is an attribute, not a method, without parentheses (), which we specify in order to distinguish it from the length () method of String.

Storage of 5.3.2 arrays

The array is stored in the contiguous memory space of the Java heap. If there is not enough heap space, the OutofMemoryError will be thrown when the array is created:

Java> int[], xLargeArray = new, int[10000000*1000000000], java.lang.OutOfMemoryError:, Java, heap, space

Different types of arrays have different types, such as the following example, intArray.getClass (), which is different from floatArray.getClass ()

Java> int[] intArray = new int[10] int[] = intArray [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] java> float[] floatArray = new float[10] float[] = floatArray [0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0] java> intArray.getClass (java.lang.Class); res5 = class [I java> floatArray.getClass res7 = class [F (java.lang.Class)

We cannot store the double value in the int array, otherwise it will lead to a compilation error.

Java> intArray[5]=1.2, ERROR:, incompatible, types:, possible, lossy, conversion, from, double, to, int, intArray[5]=1.2, ^

But the reverse is OK

Java> floatArray[5]=1 java.lang.Float res8 = 1

Because Java has the type of default conversion mechanism.

5.3.3 traversal array elements

The for loop is a convenient way to iterate over entire arrays. We can use the for loop to initialize the entire array, access to each index, or update, to obtain the array elements.

Int[], numbers = new, int[]{10, 20, 30, 40, 50}; for (int = I = 0; I, < numbers.length; i++) {System.out.println (` element, at, index) + I + ':' + numbers[i])}


Element, at, index, 0:10,
, element, at, index, 1:20,
, element, at, index, 2:30,
, element, at, index, 3:40,
, element, at, index, 4:50

Java5 begins to provide the for each loop, using the for each loop to avoid ArrayIndexOutOfBoundException. Here is an example of the iteration of the for each loop:

For (int, i:, numbers) {System.out.println (I)}


As you can see, the for each loop does not need to check the array index. This is a good method if you want to access all of the elements one by one.

But at the same time, we cannot modify the value of the array element because we cannot access the index.

5.4 array operations, commonly used API

In this section, we introduce the common operations of arrays, including Arrays classes, API, copy arrays, and so on.

Java API provides some convenient method to operate an array by java.utils.Arrays method, with rich through the use of the Arrays class, we can sort the array, you can also quickly find two array elements etc..

The common methods for the Arrays class are shown in the following table:

Method Function description
ToString () Returns the elements of an array in a string such as [1, 2, 3, 4, and 5]
AsList Array to List
CopyOf () Copies an array into a new array
(sort) Arrange the elements in the array in ascending order
BinarySearch () Two – point lookup method: finds the specified element in an array and returns the index of the element. If not found, return -1. Note: when using two – point lookups, the array should be sorted first.

Arrays.toString: convert an array into a string

If we call the default toString method of the Object object directly to an array, we will get the following output

Java> X, int[], x = [1, 2, 3, 4, 5], java>, x.toString (), java.lang.String, res33 = [[email protected]"

Such information is usually not what we want. The Arrays.toString () method provides a more useful output

Java> Arrays.toString (x), java.lang.String, res34 = [1, 2, 3, 4, 5]"

Arrays.toString provides the following 8 signatures for the basic type

ToString (boolean[] a)
toString (byte[] a)
toString (char[] a)
toString (double[] a)
toString (float[] a)
toString (int[] a)
toString (long[] a)
toString (short[] a)

For reference types, the toString (Object[], a) method is provided. Here is an example of toString passing in a reference type parameter.

Person[] persons = new Person[2]; Person Jack = new Person (); jack.name = ` Jack '; jack.age = 18; persons[0] = jack; persons[1] = new, Person (); println (Arrays.toString (persons));


[Person{name=’Jack’, age=18}, Person{name=’null’, age=0}]

Among them, the Person class code is as follows

Class Person {String name; int age; @Override public String toString (return) {"Person{" + "name='" + name +'/'' + "age=" + age +'}'; public String (getName)} {return name;} public void setName (String name) {this.name = name;} public int getAge (return) {age}; public void setAge (int age) {this.age = age;}}

Arrays.asList: array to List

Arrays in Java can be easily converted to ArrayList. ArrayList is a collection class with a very high frequency. The advantage of ArrayList is that you can change the size of the capacity, and the dynamic expansion of ArrayList is achieved by creating a larger capacity array, and then copying the elements of the current array to this new array.

Code example

Integer[] bigX = {1,2,3}; List< Integer> bigXlist = Arrays.asList (bigX); println ("bigXlist size:"); bigXlist.size (+) println (JSON.toJSONString (bigXlist)); String[] {s = "a", "B", "C"}; List slist = Arrays.asList (s); println ("slist size: (slist.size) + (JSON.toJSONString); println (slist));


BigXlist size: 3,
, [1,2,3],
, slist, size:, 3,
[a, B, C]

By turning the array into List, we can easily use the commonly used tool class methods of the collection class. For example, if we want to check whether an array contains a value, we can implement the following

String[] {s = "a", "B", "C"}; List slist = Arrays.asList (s); Boolean B = slist.contains ("a"); System.out.println (b); / / true

It’s important to note that if we call the Arrays.asList method on the array that uses the basic type to declare, the result might not be what we want

Int[] x = {1,2,3}; List< int[]> xlist = Arrays.asList (x); println (` xlist, size: '+ xlist.size ()); println (JSON.toJSONString (xlist));


Xlist size: 1

This xlist of size is actually 1? Curious. And int[] elementOfXList = xlist.get (0). This is the same as without calling asList, and we still have an array.

In fact, this is related to the implementation of Arrays.asList itself.

When the array is declared with the int[] type, the ArrayList constructor here has the array parameter type
int[1][], as shown in the following figure

uses the int[] type to declare the ArrayList constructor array parameter of the array

When we use the Integer type to declare an array, the ArrayList constructor here has the array parameter type Integer[3], as shown in the following figure

uses the Integer[] type to declare the ArrayList constructor array parameter of the array

So, let’s not use the Arrays.asList method to transform the array of primitive type declarations. If you want to convert, you must use the basic type of wrapper type so that you can get the results you want.

Arrays.copyOf: copy array

The java.lang.System class provides a native method to copy elements to another array. The arraycopy method is signed as follows

Public, static, native, void, arraycopy (Object, SRC, int, srcPos, Object, DeST, int, destPos, int, length);

We can specify the copy index position of the source array SRC by the srcPos parameter, DeST is the target array, destPos is the copy, subscript position of the target array, and the length parameter specifies the copy length.. Code example:

We first create the source array

Java> String[], SRC = {, Java, Kotlin, Scala, JS}, java.lang.String[], SRC = [Java ',' Kotlin ',' Scala ',' JS']

target array

Java> String[], DeST = new, String[7], java.lang.String[], DeST = [null, null, null, null, null, null, null]

Copy from index 0, copy all SRC elements into dest

System.arraycopy (SRC, 0, DeST, 0, src.length)


Java> DeST, java.lang.String[], DeST = [Java ',' Kotlin ',' Scala ',' JS', 'null', 'null', 'null]', ',', '

If the number of source data exceeds the target array boundary, the IndexOutOfBoundsException exception is thrown

Java> System.arraycopy (SRC, 0, DeST, 0, 10) java.lang.ArrayIndexOutOfBoundsException

As you can see, using the System.arraycopy method, we also have to create a dest array. It’s a bit of a bother. Don’t worry, the copyOf method has been prepared for us in the Arrays class. We can call the copyOf method directly to expand the array. The function is defined as follows

Public, static, < T> T[] copyOf (T[], original, int, newLength) {return (T[]) copyOf (original, newLength, original.getClass ())}

Among them, the implementation of the method calls copyOf implementation, as follows

Public static < T, U> T[] copyOf (U[] original, int newLength, Class< extends? T[]> newType) {@SuppressWarnings ("unchecked") (copy = T[] (Object) = newType (Object) Object[].class (T[]) new Object[)? NewLength] (T[]): Array.newInstance (newType.getComponentType (newLength).); System.arraycopy (original, 0, copy, 0, Math.min (original.length, newLength)); return copy;}

We can see that its internal implementation calls the System.arraycopy method as well. It is equivalent to a higher level of abstraction of the System.arraycopy method. In programming, it is one of the most essential and practical methodologies to carry out the abstraction from the upper level.

Code example:

Java> s = Arrays.copyOf (s, s.length * 2), java.lang.String[], s = [Java ',' Kotlin ',' Scala ',' JS', 'null', 'null', 'null', 'null]', ',', '

Arrays.sort: array element sorting

Ascending sorting of array elements. Code example

Java> Integer[] x = {10,2,3,4,5} java.lang.Integer[] x = [10, 2, 3, 4, 5] java> Arrays.sort (x); java> X; java.lang.Integer[] x = [2, 3, 4, 5, 10] java> String[] s = {"ABC", "CBA", "BCA java.lang.String[] s"} = ["ABC", "CBA", "BCA" java> (s); Arrays.sort java> s java.lang.String[] s = "ABC", "BCA", "CBA"]

It should be noted that when you call the sort method, the elements in the incoming array cannot have null values, otherwise the null pointer exception will be reported

String[] {s = "JS", "Java", "Kotlin", "Scala", null, null, null, null} java.lang.String[] s = "JS", "Java", "Kotlin", "Scala", null, null, null, null], java> Arrays.sort (s) java.lang.NullPointerException

Arrays.binarySearch: in the incoming array, two points are searched for the specified element

Let’s start with a simple code example to see how this method works

Java> Integer[] x = {2,3,4,5,10} java.lang.Integer[] x = [2, 3, 4, 5,10] java> Arrays.binarySearch (x, 3) java.lang.Integer java> Arrays.binarySearch (res40 = 1; X, 10) java.lang.Integer java> Arrays.binarySearch (res41 = 4; X, 0) java.lang.Integer res42 = -1

Returns an index if the element is found; returns -1 if it is not found.

The binarySearch method is defined as follows

Public, static, int, binarySearch (int[], a, int, key) {return, binarySearch0 (a, 0, a.length, key)}

Among them, binarySearch0 is the implementation of the standard two bit search algorithm

Private static int binarySearch0 (int[] a, int fromIndex, int toIndex, int key) {int low int = fromIndex; high = toIndex - 1; while (low = < high) {int = mid (low + high) > > > int 1; midVal = a[mid]; if (midVal < key; Low = mid + 1); else if (midVal > key) high = mid - 1; else return mid; / / key found return} - (low + 1); / / key not found.}

The two – point lookup algorithm requires that the array to be found must be ordered. If unordered lookups are available, we can usually just walk through all the indexes to search for them. The code reads as follows

Public int search (int[] nums, int target) {/ / for (int i=0 traversal of each element; i< nums.length; i++) {if (nums[i] = = target) {return I; / / find elements, return the subscript}} / / if target didn't find return -1;}

5.5 multidimensional array

Let’s start by creating a multidimensional array of 2 rows and 3 columns:

Java> int[][], multiArray = new, int[2][3], int[][], multiArray = [[0, 0, 0], [0, 0, 0]]

This is an array of length 2, and each element of it (such as [0, 0, 0]) holds an array of length 3. Multidimensional arrays can also be called nested arrays. Here is an example of initializing a multidimensional array:

Java> int[][], multiArray = {{1,2,3}, {10,20,30}}, int[][], multiArray = [[1, 2, 3], [10, 20, 30]], java>, multiArray[0], int[], res44 = [1, 2, 3], java>, multiArray[1],, 30], int[], res45 = [10, 20

We can use the following graph to illustrate the meaning of multidimensional arrays visually

multidimensional array schematic diagram

A multidimensional array is an array of elements with arrays. The two-dimensional array above is a special one-dimensional array, each of which is a one-dimensional array.

We can first declare the length of the first dimension of a multidimensional array, and the length of the second dimension can be declared separately at initialization time. Such as:

We first declare an array of 2 rows, where we do not specify the length of each column element. The code reads as follows

Java> String[][], s = new, String[2][], java.lang.String[][], s = [null, null]

As follows

declares an array of 2 rows

We assign values to each row element, and we assign the value to each line as a String array

Java> s[0] = new String[2] java.lang.String[] = res46 [null, null] java> s[1] String[3] = new java.lang.String[] res47 = [null, null, null] java> s java.lang.String[][] s = [[null, null], [null, null, null]]

Among them, s[0]=new, String[2], and s[1]=new String[3] are the lengths that limit each array of second dimensions.

As shown in the following figure

, s[0]=new, String[2], and s[1]=new String[3]

At this point, we have basically seen the structure of this multidimensional array, [[null, null], [null, null, null]]. The first line is an array of 2 elements, and the second line is an array of 3 elements.

Then, we assign values to elements of each row and column

Java> s[0][0] = new String ("Java"); java.lang.String res49 = "Java" java> s[0][1] = new String ("Scala"); java.lang.String res50 = "Scala" java> s[1][0] = new String ("Kotlin"); java.lang.String res51 = "Kotlin" java> s[1][1] = new String ("SpringBoot"); java.lang.String res52 = "SpringBoot" java> s[1][2] = new String ("JS"); java.lang.String res53 = "JS"

Finally, our array is initialized to

Java> s java.lang.String[][] = "s" Java "," Scala "], [" Kotlin "," SpringBoot "," JS ""

The element reference in a two-dimensional array is arrayName[index1][index2]. The code example is as follows

Java> s[0][1], java.lang.String, res54 = Scala, java> s[1][0], java.lang.String, res55 = Kotlin"

Accessing elements that do not exist also throw ArrayIndexOutOfBoundsException exceptions

Java> s[0][2] java.lang.ArrayIndexOutOfBoundsException: 2


Sample code for this chapter: https://github.com/EasyJava2017/basics