Talking about the difference between Array (Array) and List (ArrayList) in Java, introducing common methods of Arrays

Table of contents

1. The difference between an array and a list

1. Array (Array)

(1) Array (Array)

(2) Declaration and creation of arrays

(3) Multidimensional array

(4) Advantages and disadvantages of arrays

2. List (ArrayList)

(1) List (ArrayList)

(2) Declaration and creation of lists

(3) Advantages and disadvantages of the list

3. The difference between Array (Array) and List (ArrayList)

(1) Space size

(2) Storage content

(3) Delete method

2. Common methods of the Arrays class

1. Assignment

fill()

2. Sort

sort()

3. Find

binarySearch()

4. Compare

equals()

5. Copy

copyOf()

copyOfRange()


The java.util.Arrays class is a tool class for manipulating arrays, including various methods for manipulating arrays, allowing arrays to be treated as lists

1. The difference between an array and a list

1. Array (Array)

(1) Array (Array)

        Arrays provided in the Java language are used to store elements of the same type with a fixed size.

  • An array is a linear data structure in data structures.
  • An array can be said to be a container or a collection.
  • Only data of the same type can be stored in an array, and the data type must be specified when defining an array.
  • If you want to add different data types to the array, just define the type of the array as Object.
  • The number of elements that an array can store is fixed, because the length of the array must be specified when it is defined.
  • Arrays in Java are classes, which have only one property length (the length of the array).
  • The calculated value of the length attribute is calculated from 1, and the subscript of the array is calculated from 0.

(2) Declaration and creation of arrays

        Array variables must first be declared before the array can be used in the program.

dataType[] arrayRefVar; (preferred) or dataType arrayRefVar[];                

        Java uses the new operator to create arrays.

arrayRefVar = new dataType[arraySize]; 

        We can also complete the declaration and creation with a single statement:

dataType[] arrayRefVar = new dataType[arraySize];

         We can also create arrays like this:

dataType[] arrayRefVar = {value0,value1,value2,value3,value4,value5};

(3) Multidimensional array

        Java does not have the concept of multidimensional arrays. From the perspective of the underlying operating mechanism of arrays, Java does not have multidimensional arrays, but Java provides a syntax that supports multidimensional arrays, which can realize the functions of multidimensional arrays.

        The array type in the Java language is a reference type, so the array variable is actually a reference, and this reference points to the real array memory. The type of the array element can also be a reference, if the reference of the array element points to the real array memory again, this situation looks a lot like a multidimensional array.

       Therefore, a multidimensional array can be regarded as an array of arrays. For example, a two-dimensional array is a special one-dimensional array, and each element is a one-dimensional array.

Dynamic initialization of multidimensional arrays (take two-dimensional as an example)

type[][] typeName = new type[typeLength1][typeLength2];   (首选)

type[] typeName[] = new type[typeLength1][typeLength2]; 

type typeName[][] = new type[typeLength1][typeLength2]; 

(typeLength1 is the number of rows, typeLength2 is the number of columns)

Since multidimensional arrays can be regarded as arrays of arrays, we can also allocate reference space for each dimension separately

String[][] str = new String;

str[0] = new String[2]; //The two-dimensional array has 2 rows

str[1] = new String[2]; //The two-dimensional array has 2 columns

References to multidimensional arrays (take two-dimensional as an example)

For each element in the two-dimensional array, the reference method is arrayName[index1][index2], index1 is the row index, index2 is the column index

str[1][0]; //The second row and the first column

(4) Advantages and disadvantages of arrays

Advantages: Arrays are the fastest storage and retrieval speeds of all data structures.

Disadvantages: The length of the array is fixed. It is inconvenient to delete or add data, and the space will be wasted when deleting. If the data is full when adding, new data cannot be added.

2. List (ArrayList)

The list in this article is mainly used for comparison with arrays. The implementation of ArrayList is based on arrays, and the implementation of LinkedList is based on doubly linked lists. Therefore, this article mainly introduces ArrayList.

(1) List (ArrayList)

The ArrayList class is an array that can be dynamically modified. The difference from ordinary arrays is that it has no fixed size limit, and we can add or delete elements.

(2) Declaration and creation of lists

The ArrayList class is located in the java.util package and needs to be imported before use

import java.util.ArrayList;

 

ArrayList<E> objectName = new ArrayList<>();      

//E: Generic data type, only reference data type

(3) Advantages and disadvantages of the list

advantage:

  • Support automatic resizing
  • Elements can be inserted flexibly
  • Elements can be removed flexibly

Disadvantages: sacrifice efficiency, slower than general arrays

3. The difference between Array (Array) and List (ArrayList)

List (ArrayList) is an enhancement to Array (Array)

(1) Space size

  • The space size of Array is fixed, and you cannot apply again if the space is not enough, so you need to determine the appropriate space size in advance.
  • The space of ArrayList is dynamically increased. If there is not enough space, it will create a new array with a space 0.5 times larger than the original space, then copy all elements to the new array, and then discard the old array. Moreover, every time a new element is added, it is checked whether there is enough space in the internal array.

(2) Storage content

  • Arrays can contain both primitive types and object types.
  • ArrayList can only contain object types.

(3) Delete method

  • The Array array does not provide a delete method
  • There is remove() method in ArrayList

Suggestion: Based on efficiency and type inspection, use Array as much as possible, use ArrayList when the size of the array cannot be determined, and
use ArrayList when solving generalization problems.

2. Common methods of the Arrays class

The methods in the Arrays class are all modified by static (that is, static methods), so the methods can be called directly in the form of Arrays.xxx(xxx) . The following introduces some common methods of the Arrays class. The common methods can be roughly divided into: assignment, sorting , find, compare, copy

1. Assignment

fill()

Assigns the specified value to each element in the specified range of the specified array.

public static void fill(arrayname,value)

or

public static void fill(arrayname ,starting index ,ending index ,value)

import java.util.*;
public class Example{
    public static void main(String[] args) {
        int array[] = new int[10];
        Arrays.fill(array, 1);
        for (int arrays:array) {
            System.out.print(arrays+" ");
        }
        System.out.println();
        Arrays.fill(array, 3, 6, 9);
        for (int arrays:array) {
            System.out.print(arrays+" ");
        }
    }
}
1 1 1 1 1 1 1 1 1 1 
1 1 1 9 9 9 1 1 1 1 

2. Sort

sort()

Sorts the specified array of objects in ascending order according to the natural order of its elements.

public static void sort(Object[] arrayname)     

//Sort all elements of an array in ascending order

public static void sort(Object[] arrayname,int fromIndex, int toIndex)

//Sort the array part, that is, sort the elements of the subscript of the array a from fromIndex to toIndex-1

import java.util.*;
public class Example{
    public static void main(String[] args) {
        int array[] = {2,5,85,30,75,66,-18,0};
        Arrays.sort(array,2,5);
        for (int arrays:array) {
            System.out.print(arrays+" ");
        }
        System.out.println();
        Arrays.sort(array);
        for (int arrays:array) {
            System.out.print(arrays+" ");
        }
    }
}
2 5 30 75 85 66 -18 0 
-18 0 2 5 30 66 75 85 

The underlying principle of Arrays.sort():

Suppose the array length is n

  • 1<=n<47, use insertion sort
  • 47<=n<286, use quick sort
  • n>=286, use merge sort or quick sort (use merge sort in a certain order, use quick sort in no order)

Here is a simple understanding. Regarding the principle and recurrence of various sorting algorithms, I will post a separate blog to explain it when I talk about the algorithm.

3. Find

binarySearch()

Searches the given array for an object with the given value using the binary search algorithm.

The array must be sorted before calling.

public static int binarySearch(Object[] a,Object key)

// Find all elements in an array

return value:

  • In the range of the array, the index value is "-insertion point index value"
  • Less than the elements in the array, the index value is – 1
  • Greater than the elements in the array, the index value is – (length + 1)

public static int binarySearch(Object[] a,int fromIndex,int toIndex,Object key)

// Search within the range specified by the array

return value:

  • In the search scope, the index value is "-insertion point index value"
  • Less than the element in the search range, return –(fromIndex + 1)
  • Greater than the element in the search range, returns –(toIndex + 1)
import java.util.*;
public class Example{
    public static void main(String[] args) {
        int array[] = {2,5,85,30,75,66,-18,0};
        Arrays.sort(array);
        for (int arrays:array) {
            System.out.print(arrays+" ");
        }
        System.out.println();
        System.out.println(Arrays.binarySearch(array,5));
        System.out.println(Arrays.binarySearch(array,-99));
        System.out.println(Arrays.binarySearch(array,100));
        System.out.println(Arrays.binarySearch(array,60));
        System.out.println(Arrays.binarySearch(array,1,5,5));
        System.out.println(Arrays.binarySearch(array,1,5,-99));
        System.out.println(Arrays.binarySearch(array,1,5,100));
        System.out.println(Arrays.binarySearch(array,1,5,60));
    }
}
-18 0 2 5 30 66 75 85 
3         //5在数组内,返回排完序后的索引3
-1        //-99小于数组内元素,返回索引值为-1
-9        //100大于数组内元素,返回索引值为-(length+1)=-(8+1)
-6        //60在数组范围内,返回索引值为-插入点索引值=-6
3         //5在搜索范围内,返回排完序后的索引3
-2        //-99小于搜索范围内元素,返回–(fromIndex + 1)=-(1+1)=-2
-6        //100大于搜索范围内元素,返回–(toIndex + 1)=-(5+1)=-6
-6        //60在搜索范围内,索引值为-插入点索引值=-6

The principle and recurrence of the binary search algorithm will also be mentioned in future blogs

4. Compare

equals()

Returns true if the two specified arrays are equal to each other. Two arrays are considered equal if they contain the same number of elements and all corresponding pairs of elements in both arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.

public static boolean equals(Object[] arrayname,Object[] arrayname2)

import java.util.*;
public class Example{
    public static void main(String[] args) {
        int[] array1 = {2,5,85,30,75,66,-18,0};
        int[] array2 = {75,2,66,30,5,85,0,-18};
        
        if(Arrays.equals(array1, array2)){
            System.out.println("array1等于array2");
        }
        else{
            System.out.println("array1不等于array2");
        }
        
        Arrays.sort(array1);
        Arrays.sort(array2);
        
        for(int arrays:array1){
            System.out.print(arrays+" ");
        }
        System.out.println();
        for(int arrays:array2){
            System.out.print(arrays+" ");
        }     
        System.out.println();
        
        if(Arrays.equals(array1, array2)){
            System.out.println("排序后,array1等于array2");
        }
        else{
            System.out.println("排序后,array1不等于array2");
        }
    }
}
array1不等于array2
-18 0 2 5 30 66 75 85 
-18 0 2 5 30 66 75 85 
排序后,array1等于array2

5. Copy

copyOf()

Copy the elements of the original array to the new array, and you can set the length of the copy (that is, the number of elements that need to be copied)

public static Object[] copyOf(original,newLength)

copyOfRange()

Copies a range of elements into a new array

public static Object[] copyOfRange(original,int from,int to)

//from is the start position of the copy (included), to is the end position of the copy (not included)

import java.util.*;
public class Example{
    public static void main(String[] args) {
        int[] array1 = {2,5,85,30,75,66,-18,0};
        int[] array2 = Arrays.copyOf(array1, 6);
        int[] array3 = Arrays.copyOfRange(array1, 2, 4);
        System.out.println(Arrays.toString(array1));
        System.out.println(Arrays.toString(array2));
        System.out.println(Arrays.toString(array3));       
    }
}
[2, 5, 85, 30, 75, 66, -18, 0]
[2, 5, 85, 30, 75, 66]
[85, 30]

Guess you like

Origin blog.csdn.net/senxu_/article/details/126272908