Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

A complete summary of java array operation application knowledge


May 10, 2021 Java


Table of contents


Arrays are a very useful and commonly used data type that exists in every program language, and arrays in java are the simplest composite data types, and most of the whites who have just learned java arrays hear the saying that java is a pure object-oriented language, and its array is also an object. S o a lot of people use arrays in the same way as an object, and then you'll find out how "unnatural" it is to use arrays as a class in terms of implementation. Here's a full look at the arrays in java.


A complete summary of java array operation application knowledge

What is an array

An array is a collection of data of the same type and is actually a container. T here is a lot of data involved in the operation, so what needs to be done first. Not how to work but how to save this data for later operations, then array is a way to store data, can store data where we call containers, containers contain things are elements of arrays, arrays can hold any type of data, although you can hold any type of data, but a defined array can only install one element, that is, once defined, then the data type stored inside is determined.

The characteristics of the array

1. In Java, there are boundary checks, whether using arrays or collections. If you cross the line, you get a RuntimeException exception.

2. Arrays can only hold specific types. A rrays can hold native data types, but collections cannot. Collections do not handle objects by specific type, they treat all objects by Object type, and the collection contains references to objects rather than objects themselves.

3. Collection classes can only save references to objects. A rrays can be created between saving native data types directly or saving references to objects. Wrapper Class can be used in collections, such as Integer, Double, and so on, to save native data type values.

4. The object array and the native data type array are almost identical in use; the only difference is that the object array holds a reference, and the native data type array holds the value of the native data type.

int a = 10;
 
Integer integer = new Integer(a);
 
int b = integer.intValue();
 
System.out.println(a = b);

The correct use of the array

If you need to store a lot of data, for example, if you need to read 100 numbers, then you need to define 100 variables, obviously it doesn't make much sense to write 100 codes over and over again. T o solve this problem, the Java language provides the data structure of an array, a container that can store elements of the same data type and store 100 numbers in an array. At this time the array is of great help


The format of the array

Format 1:

The name of the element type, the array name, the new element type, the number of elements or the length of the array;
int[] arr = new int[5];
 
arr[0] = 1;
 
arr[1] = 2;

Format 2:

The name of the element type, the array name, the new element type, the element, the ,......;
int[] arr = new int[]{3,5,1,7};
 
int[] arr = {3,5,1,7};

Note: When allocating space to an array, you must specify the number of elements that the array can store to determine the size of the array. Y ou cannot modify the size of an array after you create it. You can use the length property to get the size of the array.

Declare array variables

In order to use an array, you must declare the array in the program and specify the element type of the array, the left half:
Write the left side to clarify that the element type is int, the container uses an array, so how do you identify the array? To use an array you need to give the array a name, so here we name the array arr . and keep up with the equal sign.

The code embodies:
int [] arr
Example:
String[] aArray = new String[5];  
String[] bArray = {"a","b","c", "d", "e"};  
String[] cArray = new String[]{"a","b","c","d","e"}; 
Note: int arr is also a format for creating arrays. It is recommended to declare an array in the form of int.arr.

The three ways and differences in creating arrays

public static void main(String[] args) {  
    // 1.方式一  声明 分配空间并赋值  
    int[] arr1 = {1,2,3};  
    // 2.方式二 显示初始化  
    int[] arr2;  
    arr2 = new int[]{1,2,3};   
    // 3.方式三 显示初始化()  
    int[] arr3;  
    arr3 = new int[3];  
}  
Their difference, the way one: in the declaration of the time directly already allocated space, and assigned, the way one can not be written in the following form.
int[] arr1;  
arr1 = {1,2,3};//错误写法 编译不同过  
Ways two and three, declarations and memory allocations are separate, as in the example above,
int[] arr2;  和  int[] arr3;  
This step is to assign a reference to the stack space, which holds a reference, null
arr2 = new int[]{1,2,3};<span style="font-family: Arial, Helvetica, sans-serif;">arr3 = new int[3];</span>  
It is only at this point that jvm begins to allocate space in the memory heap area and assigns a value by two direct assignments of 1,2,3 ways three default initialization, the basic type is 0 boolean type is false reference type null,

Note: Once the memory is allocated cannot be changed, all say the array length is fixed

A complete summary of java array operation application knowledge

Array initialization

Mode 1: Do not use the operator new
int[]arr = { 1, 2, 3, 4, 5 };
Mode 2: Use the operator new
int[] arr2 = new int[] { 1, 2, 3, 4, 5 };
int[] arr3=new int[3];
arr3[0]=1;
arr3[1]=5;
arr3[2]=6;
If the operator new is not used in array initialization. It is important to note that the following is incorrect.
int[] arr;
arr={1,2,3,4,5};

At this point, the initialization array must be declared, created, and initialized in one statement, resulting in syntax errors.

So you can only write as follows:

int[] arr={1,2,3,4,5};


java.util.Arrays

Arrays class is a very useful array tool class, there are many tool methods, retrieval, filling, sorting, comparison, toString() and so on.

Here's an example:
import java.util.Arrays; 

/** 
* 数组综合测试 
* 
* @author leizhimin 2009-7-28 12:35:41 
*/ 
public class TestArrays { 
        public static void main(String[] args) { 
                int[] i = new int[10]; 
                //填充数组 
                Arrays.fill(i, 2); 
                //遍历数组 
                for (int x : i) { 
                        System.out.print(x + " "); 
                } 
                //toString()数组 
                System.out.println("\n" + Arrays.toString(i)); 
                //复制数组 
                int[] b = new int[12]; 
                System.arraycopy(i, 0, b, 2, 5); 
                System.out.println(Arrays.toString(b)); 
                //一维数组的比较 
                int[] c = new int[3]; 
                int[] d = new int[3]; 
                Arrays.fill(c, 3); 
                Arrays.fill(d, 3); 
                System.out.println(c.equals(d)); 
                System.out.println(Arrays.equals(c, d)); 
                System.out.println("-------------"); 
                int[][] a1 = {{1, 2, 3}, {4, 5, 6}}; 
                int[][] a2 = {{1, 2, 3}, {4, 5, 6}}; 
                System.out.println(a1.equals(a2)); 
                System.out.println(Arrays.equals(a1, a2)); 
                System.out.println(Arrays.deepEquals(a1, a2)); 
                //深度toString() 
                System.out.println(Arrays.toString(a1)); 
                System.out.println(Arrays.deepToString(a1)); 

                //数组的排序 
                int[] a3 = {3, 2, 5, 4, 1}; 
                System.out.println(Arrays.toString(a3)); 
                Arrays.sort(a3); 
                System.out.println(Arrays.toString(a3)); 
                //一维数组数值检索 
                int index1 = Arrays.binarySearch(a3, 4); 
                int index2 = Arrays.binarySearch(a3, -12); 
                int index3 = Arrays.binarySearch(a3, 8); 
                System.out.println(index1 + " " + index2 + " " + index3); 
        } 
}

Results:
2 2 2 2 2 2 2 2 2 2    
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2] 
[0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0] 
false 
true 
------------- 
false 
false 
true 
[[I@3e25a5, [I@19821f] 
[[1, 2, 3], [4, 5, 6]] 
[3, 2, 5, 4, 1] 
[1, 2, 3, 4, 5] 
3 -1 -6 

Process finished with exit code 0

The traversal of the array

public static void main(String[] args) {
int[] x = { 1, 2, 3 };
for (int y = 0; y < 3; y++) {
System.out.println(x[y]);
// System.out.println("x["+y+"]="+x[y]); 打印效果 x[0]=1;
} // 那么这就是数组的第一个常见操作.遍历
}

There is a property in the array that gets the number of elements in the array, that is, the length of the array. Array name.length
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
for (int y = 0; y < x.length; y++) {
System.out.println(x[y]);
// System.out.println("x["+y+"]="+x[y]); 打印效果 x[0]=1;
} // 那么这就是数组的第一个常见操作.遍历
}

A complete summary of java array operation application knowledge

The replication of the array

java.lang.System
 
public static void arraycopy(Object src,
                             int srcPos,
                             Object dest,
                             int destPos,
                             int length)

Parameters:
src - Source array.
srcPos - the starting position in the source array.
dest - Target array.
destPos - The starting position in the target data.
length - The number of array elements to copy.

Common exceptions to arrays

1, array corner marker cross-border exception: Note: array corner from 0.
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
System.out.println(x[3]);
//java.lang.ArrayIndexOutOfBoundsException
}
2, empty pointer exception:
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
x = null;
System.out.println(x[1]);
// java.lang.NullPointerException
}
Array:
When to use arrays: When there are more elements to facilitate the operation of these arrays, will be stored temporarily first, the container used is the array.

Characteristics:
The length of the array is fixed.

Common operations of arrays

1, an array to remove the maximum value

Defines a feature that gets the maximum value:
1, determine the result: return value type int
2, unknown content: to get which array of the maximum value is not determined, is the array is not determined
Ideas:
1, define a variable that records the larger elements of the array.
2, traversing the entire array, so that each element of the array and the variable can be compared.
3. When a variable encounters an element larger than it, let the variable record the value of the element, and when the loop ends, the maximum value is generated
*/
public static int getMax(int[] arr)
{
//定义变量记录较大的值,初始化为数组中的任意一个元素。
int max = arr[0];
for(int x=1; x<arr.length; x++)
{
if(arr[x]>max)
max = arr[x];
}
return max;
}

2, direct sorting

Sort arrays with direct sorting:

/*

Select the sort.

Compare elements with one corner and other elements.

At the end of the inner loop for the first time, the most value appears at the header position.

*/
public static void selectSort(int[] arr)
{
for(int x=0; x<arr.length-1; x++)
{
for(int y=x+1; y<arr.length; y++)//为什么y的初始化值是 x+1?因为每一次比较,
//都用x角标上的元素和下一个元素进行比较。
{
if(arr[x]>arr[y])
{
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
 }

3, bubbling sort

/*
冒泡排序。
比较方式:相邻两个元素进行比较。如果满足条件就进行位置置换。
原理:内循环结束一次,最值出现在尾角标位置。
*/
public static void bubbleSort(int[] arr)
{
for(int x=0; x<arr.length-1; x++)
{
for(int y=0; y<arr.length-x-1; y++)//-x:让每次参与比较的元减。
//-1:避免角标越界。
{
if(arr[y]>arr[y+1])
{
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1] = temp;
}
}
}
}

A complete summary of java array operation application knowledge
4, half-look (two-way method)
/*
为了提高查找效率,可使用折半查找的方式,注意:这种查找只对有序的数组有效。
这种方式也成为二分查找法。
*/
public static int halfSeach(int[] arr,int key)
{
int min,mid,max;
min = 0;
max = arr.length-1;
mid = (max+min)/2;
while(arr[mid]!=key)
{
if(key>arr[mid])
min = mid + 1;
else if(key<arr[mid])
max = mid - 1;
if(min>max)
return -1;
mid = (max+min)/2;
}
return mid;
}

5, array flip
/*
反转其实就是头角标和尾角标的元素进行位置的置换,
然后在让头角标自增。尾角标自减。
当头角标<尾角标时,可以进行置换的动作。
*/
public static void reverseArray(int[] arr)
{
for(int start=0,end=arr.length-1; start<end; start++,end--)
{
swap(arr,start,end);
}
}
//对数组的元素进行位置的置换。
public static void swap(int[] arr,int a,int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}

6, multi-dimensional array
In the Java language, a multi-dimensional array is treated as an array of arrays.

(1) Definition of a two-dimensional array
type arrayName[ ][ ];   
type [ ][ ]arrayName; 

(2) Initialization of a two-dimensional array

Static initialization
int intArray[ ][ ]={{1,2},{2,3},{3,4,5}}; 
In the Java language, because two-dimensional arrays are considered arrays, array space is not allocated continuously, so each dimensional array is not required to be the same size.

Dynamic initialization
Allocate space directly for each dimensional in the following format:
arrayName = new type[arrayLength1][arrayLength2];   
int a[ ][ ] = new int[2][3]; 
Starting with the highest dimensionality, allocate space for each dimensional:
arrayName = new type[arrayLength1][ ];   
arrayName[0] = new type[arrayLength20];   
arrayName[1] = new type[arrayLength21];   
…   
arrayName[arrayLength1-1] = new type[arrayLength2n]; 
Example: Dynamic initialization of an array of two-dimensional simple data types is as follows:
int a[ ][ ] = new int[2][ ];   
a[0] = new int[3];   
a[1] = new int[5]; 
For arrays of two-dimensional composite data types, reference space must first be allocated for the highest dimensionality, and then space must be allocated for low-dimensional secondary. Also, space must be allocated separately for each array element.

For example:
String s[ ][ ] = new String[2][ ];   
s[0]= new String[2];//为最高维分配引用空间  
s[1]= new String[2]; //为最高维分配引用空间  
s[0][0]= new String("Good");// 为每个数组元素单独分配空间  
s[0][1]= new String("Luck");// 为每个数组元素单独分配空间  
s[1][0]= new String("to");// 为每个数组元素单独分配空间  
s[1][1]= new String("You");// 为每个数组元素单独分配空间 

(3) A reference to a two-dimensional array element


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

For example:
num[1][0]; 

(4) Examples of two-dimensional arrays:

Example: Two matrices multiply each other
public 
class MatrixMultiply{   
public 
static 
void main(String args[]){   
int i,j,k;   
int a[][]=new 
int [2][3]; //动态初始化一个二维数组  
int b[][]={{1,5,2,8},{5,9,10,-3},{2,7,-5,-18}};//静态初始化  
 
一个二维数组   
int c[][]=new 
int[2][4]; //动态初始化一个二维数组  
for (i=0;i<2;i++)   
for (j=0; j<3 ;j++)   
a[j]=(i+1)*(j+2);   
for (i=0;i<2;i++){   
for (j=0;j<4;j++){   
c[j]=0;   
for(k=0;k<3;k++)   
c[j]+=a[k]*b[k][j];   
}   
}   
System.out.println("*******Matrix C********");//打印Matrix C标记  
for(i=0;i<2;i++){   
for (j=0;j<4;j++)   
System.out.println(c[j]+" ");   
System.out.println();   
}   
}   
} 

7, list to each other's conversion methods

(1) List is converted into an array. (List here is the entity is Array List)

Call the toArray method of ArrayList.

toArray

Public slt;T?t;T?toArray (T?a) returns an array that contains all elements in this list in the correct order; I f the list can be placed into a specified array, an array of elements placed in the list is returned. Otherwise, a new array is allocated based on the runtime type of the specified array and the size of the list.

If the specified array can hold the list and has room left (that is, more elements of the array than the list), the element in the array immediately following the end of the collection is set to null. This is useful for determining the length of a list, but only if the caller knows that the list does not contain any null elements.

Designated by:
ToArray in the interface Collection

Designated by:
ToArray in the interface List.lt;E.gt

Covered:
ToArray in the class AbstractCollection

Parameters:
a - To store an array of list elements, if it is large enough;

Return:
An array that contains list elements.

Thrown:
ArrayStoreException - If a's runtime type is not a super-type of runtime type for each element in this list.

Specific usage:
List list = new ArrayList();
list.add("1");
list.add("2");
final int size = list.size();
String[] arr = (String[])list.toArray(new String[size]);

(2) The array is converted to List.

Call the AsList method of Arrays.

asList

Public statics return a fixed-size list supported by a specified array. ( Changes to the returned list are "straight- to the array.) T ogether with Collection.toArray, this method acts as a bridge between array-based and collection-based APIs. The returned list is serialized and RandomAccess is implemented.

This method also provides a convenient way to create a fixed-length list that is initialized to contain multiple elements:

List stooges = Arrays.asList("Larry", "Moe", "Curly");

Parameters:

a - An array of support lists.

Return:

Specifies a list view of the array.

See also:

Collection.toArray()

Specific usage:

String[] arr = new String[] {"1", "2"};
List list = Arrays.asList(arr);