To define an array

An array is a data structure used to store a collection of values of the same type. Each value in the array can be accessed by an integer subscript. For example, if a is an integer array, a[I] is the integer with subscript I in the array. Java arrays are just like any other language. Using array storage and random access to sequences of object references is very efficient in Java. Arrays are simple linear sequences, which make access to elements very fast. This speed comes at a cost, however. The cost is that the array object’s size is fixed and cannot be changed for the lifetime of the array, so once an array has been created, it cannot be resized (although you can change every element of the array). You should use another data structure, an ArrayList. The similarity between arrays and ArrayLists is intentional, so conceptually the two are easy to switch. But as you can see in collections, collections are much more powerful than arrays. With the advent of Automatic Boxing in Java, using basic data types through collections is almost as easy as using arrays. The only remaining advantage of arrays is efficiency. However, when you solve a more general problem, arrays can be too restrictive, in which case you can use the collection class, which ArrayList will cover later.

Array creation

When declaring an array variable, you need to specify the array type (the data element type follows []) and the name of the array variable. For example, we declare an integer array a:int[] a; But this just declares an array, without any information about the data. You also initialize the array. New: int[] a = new int[100]; // An array of 100 integers, all initialized to 0. Int [] array = {1, 2, 3, 4}; Int [] array1 = new int[] {1, 2, 3, 4}; You can even initialize an anonymous array: new int[] {1, 2, 3, 4}; Create an anonymous array and copy it to array. This is an array of integers, but there are also character arrays, object arrays (String[]) and so on.

We can declare an array int[] a; Or int a []; Most Java application programmers prefer the first style because it separates the type int[] (an array of integers) from the variable names.

Array traversal

Just to separate out array traversal, there are two basic ways of traversal. The first is the traditional loop, where you get the length of the array. The length can be obtained using array.length. So traversal looks like this:

for (int i = 0; i < a.length; i ++)
        System.out.println(a[i]);
Copy the code

Second, Java has a powerful loop structure that can be used to process each element in an array (and other types of collections of elements) in turn without the distraction of specifying subscripts. Foreach, enhanced for structure. For (variable: collection) statement// Define a variable variable that holds each element in the collection and executes the corresponding statement (or block of statements, of course). The collection expression must be either an array or a class object that implements the Iterable interface. This loop should read “for each element in the collection.”

In Java, arrays of length 0 are allowed. This syntax can be useful when writing a method that results in an array, if the result happens to be empty. You can create an array of length 0: new elementType[0] Note that array length 0 is different from null.

Copy an array

In Java, you can copy an array variable to another array variable. At this point, both variables will reference the same array. Something like this:

ntD anonymous = { 17.19.23.29.31.37 };
smallPrimes = anonymous;
smallPrimes[1] = 19;
anonymous[1] = 19;
Copy the code

But. If you want to copy all the values of an array into a new array, you use the copyOf method of the Arrays class: int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers , luckyNumbers .length); The second argument is the length of the new array. This method is used to increase the size of Arrays: luckyNumbers = Array.copyof (luckyNumbers, 2 * Luckynumbers.length); If the array elements are numeric, the extra elements are assigned a value of 0; If the array element is Boolean, the value is assigned to false. Conversely, if the length is less than the length of the original array, only the uppermost data element is copied.

Array methods

Array methods are many, there are a few commonly used:

static String toString(type[]a); // Returns a string containing the data elements in A, enclosed in parentheses and separated by commas.

static type copyOf(type[]a, int length); / / in front of

static type copyOfRange(type[]a , int start, int end); // Return an array of the same type as a. The length of the array is length(end-start > length) or end-start. The array element is the value of A.

Static void sort(type[] a) uses an optimized quicksort algorithm to sort the array

static int binarySearch(type[]a, int start, int end, type v); // The binary search algorithm is used to find the value v. If the search is successful, the corresponding subscript value is returned; Otherwise, return a negative value r. -r-1 is where v should be inserted to keep a ordered.[start start subscript (containing this value). End end subscript (excluding this value).

static void fi11(type[] a , type v); // Set all the data elements of the array to V.

static boolean equals(type[]a, type[]b); // If two arrays are of the same size and the elements with the same subscript are equal, return true.

static void fill(type[] a, int v); // Set all elements of array to v (not necessarily int)

static boolean equals(type[] a, type[] b); // If two arrays are of the same size and the elements with the same subscript are equal, return true

There are some other methods, you can look it up yourself, not recorded here.

Sort an array

Sort Arrays using the sort method of the Arrays class. The universal sort function is called sort. It’s easy to use it by putting the name of the array in.

Multidimensional array

In Java, declaring a two-dimensional array is fairly simple. Sub: double[][] balances; As with one-dimensional arrays, a multidimensional array cannot be used until it is initialized with a call to new. Balances = new double[5][5]; double[] balances = new double[5]; Alternatively, if you know the array elements, you can initialize a multidimensional array using simplified writing instead of calling new. For example: int [] [] magicSquare = {{16, 3, 2, 13}, {5, 10, 11 and 8}, (9, 6, 7, 12}, {4, 15, 14, 1}}; Once the array is initialized, each element can be accessed with two square brackets; for example, balances[I][j].

Iterate over a two-dimensional array

There’s always something we need to do when we go through a set of numbers, but let’s just say print data. The first method:

            for (int j = 0; j < balances[i].length; j++) { System.out.println(balances[i][j]); }}Copy the code

The second method:

for (double[] row : a)// Loop one dimension
    for (double value : row)
        do something with value
Copy the code

Println (Arrays.deepToString(a)); system.out.println (Arrays.deepToString(a));