Introduction to using JAVA arrays

  • 2020-04-01 01:38:59
  • OfStack

There are three main differences between JAVA arrays and container classes: efficiency, type, and the ability to hold primitive types . In JAVA, arrays are the most efficient way to store and randomly access sequences of object references. An array is simply a linear sequence of Numbers, which makes element access very fast. But at the cost of this, the size of the array is fixed and cannot be changed during its lifetime.

With the advent of generics and automatic wrapping, containers can be used in basic types almost as easily as arrays. Both arrays and containers prevent you from abusing them to some extent, and if you cross the line, you'll get a RuntimeException. The only remaining advantage of arrays is efficiency, however, if you want to solve a more general problem, the array may be too constrained, so in this case the container will be chosen for the most part.

Therefore, if you are using the latest JAVA version, you should choose containers over arrays first. Refactor the program to an array only if performance has proven to be an issue and switching to an array improves performance.

[initialization]
JAVA has strict rules about array initialization, which effectively prevents array abuse. If you initialize incorrectly, you get CompileException instead of RuntimeException. You cannot do anything with the array reference without initializing it properly.
Arrays are defined as int[] array and int array[], in the first style, which separates the type from the variable name.
There are two ways to initialize an array, static initialization and dynamic initialization. Length must be specified when initializing, the length of the first dimension of the multidimensional array must be specified, and must be defined from the higher dimension to the lower dimension. The initialization action can occur anywhere in the code, whereas the {} method can only occur where the array is created. See the program for the specific initialization method:


public class javaArrayInit{
    public static void main(String args[]){
        int[] arrayA; //uninitialized
        int[] arrayB = new int[5]; //Static initialization
        //System.out.println(arrayA.length);  //CompileException
        System.out.println("arrayB length: " + arrayB.length); //Cannot get the actual number of elements saved

        arrayA = new int[10]; //Dynamic initialization
        System.out.println("arrayA length: " + arrayA.length);

        int[] arrayC = new int[]{1,2,3,4};
        System.out.println("arrayC length: " + arrayC.length);

        //int[] arrayD = new int[1]{1}; // Incorrect initialization. Cannot define and initialize values at the same time 

        int[][] arrayE = new int[1][];
        System.out.println("arrayE length: " + arrayE.length);

        //int[][] arrayF = new int[][2]; // The length of the higher dimension should be specified first 

        int[][] arrayG = new int[][]{{1,2,3,4},{5,6,7},{7,24,23,24}};
        System.out.println("arrayG length: " + arrayG.length);

        int[][][] arrayH = new int[][][]{{{1,2,3},{4,5,6},{7,8,9},{10,11,12}}};
        System.out.println("arrayH length: " + arrayH.length);

        dummyArray[] arrayI = {new dummyArray(),new dummyArray()}; //Custom array types
        System.out.println("arrayI length: " + arrayI.length);
        System.out.println("arrayI[1]: " + arrayI[1].getValue());

        dummyArray[] arrayK = new dummyArray[5];
        System.out.println("arrayK[0]: " + arrayK[0]); //null
        for(int i = 0; i < arrayK.length; i++){
            arrayK[i] = new dummyArray();
        }
        System.out.println("arrayK[0]: " + arrayK[0].getValue()); //2
    }
}
class dummyArray{
    private static int temp;
    private final int arrayValue = temp++;
    public int getValue(){
        return arrayValue;
    }
}
 Output: 
arrayB length: 5
arrayA length: 10
arrayC length: 4
arrayE length: 1
arrayG length: 3
arrayH length: 1
arrayI length: 2
arrayI[1]: 1
arrayK[0]: null
arrayK[0]: 2

"Length"
Read-only member length is part of an array object (although this variable is not actually declared in the API, it is dynamically generated at runtime) and is the only field or method that can be accessed. While the [] syntax is the only way to access the array object, the container is accessed through the get() method. You can use array.length to get the size of an Array, being careful to distinguish it from string.length () of type String. Array USES a member variable, and String USES a member method. At the same time, array.length only gets the size of the Array, not the actual number of elements in the Array. The length of a multidimensional array computes only the length of the first dimension.

public class javaArrayLength{
    public static void main(String args[]){
        int[] arrayA = new int[15];
        arrayA[1] = 1;
        arrayA[2] = 2;
        arrayA[3] = 3;
        System.out.println("arrayA length: " + arrayA.length);

        int[][] arrayB = new int[10][];
        System.out.println("arrayB length: " + arrayB.length);

        int[][] arrayC = new int[][]{{1,1,1,2,},{1,1,2,3,4,5},{4,5,6,7,7},};//Notice the comma at the end
        System.out.println("arrayC length: " + arrayC.length);

        int[][] arrayD = new int[][]{{1,1,1,2,},{1,1,2,3,4,5},{4,5,6,7,7},{}};
        System.out.println("arrayD length: " + arrayD.length);
    }
}
 Output: 
arrayA length: 15
arrayB length: 10
arrayC length: 3
arrayD length: 4

【 Arrays. The fill 】
Arrays.fill is a very limited method because it can only fill each position with the same value (if it is an object, it copies the same reference to fill it). Arrays.fill can be used to fill an entire array or a certain area of an array, but because arrays.fill can only be called with a single value, it is not very useful.

[assignment and reference]
JAVA arrays are initialized with only a reference to the array, and no storage is allocated to the array. Therefore, replication between arrays cannot simply be assigned with an "=" value, because the same object is being manipulated. The following procedure:

public class javaArrayQuote{
    public static void main(String args[]){
        String testA = "testA";
        String testB = "testB";
        String[] arrayA = new String[]{"arrayA"};
        String[] arrayB = new String[]{"arrayB"};
        testB = testA;
        testB = "testB change";
        System.out.println("I'm testA,I have no changed: " + testA);
        arrayB = arrayA;
        arrayB[0] = "arrayB have changed";
        System.out.println("I'm arrayA, I have no changed: " + arrayA[0]);

    }
}
 Output: 
I'm testA,I have no changed:testA
I'm arrayA, I have no changed:arrayB have changed

As you can see, when we change the value of arrayB[0], we change the array of references, so we output arrayA[0], which is the same as arrayB[0].

[array copy]
              Methods to copy arrays in JAVA:

              1. It is inefficient to use a FOR loop to copy all or specified elements
              2. Use the clone method to get the value of the array, not the reference. Clone, however, does not replicate a specified element and is less flexible
              3. Use the method system.arraycopy (SRC, srcPos, dest, destPos, length). The Java standard class library provides the static method system.arraycopy (), which is much faster than the for loop to copy the array. Two copies of the object will not appear. This is called shallowcopy.
                            SRC: source array;
                              SrcPos: the starting position of the source array to be copied;
                              Dest: destination array;
                              DestPos: the starting position of destination array;
                              Length: the length of a copy.
              Note: system.arraycopy () does not automatically wrap and unwrap, so both arrays must be of the same type or can be converted to the same type. This method can also be used to copy the array itself.
              Int [] test =,1,2,3,4,5,6 {0};
              System. Arraycopy (test, 0, test, 3, 3);
              Then the result is: {0,1,2,0,1,2,6};
              The test procedure is as follows:

public class javaArrayCopy{
    public static void main(String args[]){
        int[] array = {1,2,3,4,5,6,7,8,9};
        //For loop method
        int[] arrayA = new int[9];
        for(int i = 0; i < arrayA.length; i++){
            arrayA[i] = array[i];
            System.out.print(arrayA[i] + ",");
        }
        //test
        System.out.println("");
        arrayA[1] = 19;
        for(int i = 0; i < arrayA.length; i++){
            System.out.print(arrayA[i] + ",");
        }
        System.out.println("");
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + ",");
        }
        System.out.println("");

        //Clone method
        int[] arrayB = new int[9];
        arrayB = array.clone();
        //test
        arrayB[1] = 19;
        for(int i = 0; i < arrayB.length; i++){
            System.out.print(arrayB[i] + ",");
        }
        System.out.println("");
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + ",");
        }
        System.out.println("");

        //System. ArrayCopy method
        int[] arrayC = new int[9];
        System.arraycopy(array, 0, arrayC, 0, arrayC.length);
        //test
        arrayC[1] = 19;
        for(int i = 0; i < arrayC.length; i++){
            System.out.print(arrayC[i] + ",");
        }
        System.out.println("");
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + ",");
        }
    }
}

[array comparison]
Arrays provide an overloaded equals() method, overloaded for all types and objects, to compare the entire array. The condition for an array to be equal is that the number of elements must be equal, and the elements in the corresponding positions must also be equal. The comparison of multidimensional arrays USES the deepEquals() method. The array.equals () method must compare two arrays of the same type.

import java.util.Arrays;
public class javaArrayEquals{
    public static void main(String args[]){
        int[] arrayA = {1,2,3};
        int[] arrayB = {1,2,3,};
        int[] arrayC = new int[4]; //if int[] arrayC = new int[3],return true
        arrayC[0] = 1;
        arrayC[1] = 2;
        arrayC[2] = 3;
        System.out.println(Arrays.equals(arrayA, arrayB));
        System.out.println(Arrays.equals(arrayA, arrayC));

        String[][] arrayD = {{"a","b"},{"c","d"}};
        String[][] arrayE = {{"a","b"},{"c","d"}};
        System.out.println(Arrays.deepEquals(arrayD, arrayE));
    }
}

[array sorting and searching]
Arrays provide a built-in sort() method that sorts arrays of any primitive type or arrays of objects that must implement the Comparable interface or have an associated Comparator. JAVA provides different sorting methods for different types -- quicksort for primitive types and "stable merge sort" for objects, so there is no need to worry about the efficiency of array sorting.
  BinarySearch () is used to quickly find elements ina sorted array, and if you use binarySearch() on an unsorted array, it produces unpredictable results.

[return array]
C and C++ cannot return an array, only a pointer to an array, because returning an array makes it difficult to control the life cycle of an array and is prone to memory leaks. Java allows you to return an array directly and can be recycled by the garbage collector.

[unable to convert array of primitive type]

Array to List:

import java.util.*;
public class arrayToList{
    public static void main(String args[]){
        String[] arrayA = {"a","b","c"}; 
        List listA = java.util.Arrays.asList(arrayA);
        System.out.println("listA: " + listA);

        int[] arrayB = {1,2,3}; 
        List listB = java.util.Arrays.asList(arrayB);
        System.out.println("listB: " + listB);

        Integer[] arrayC = {1,2,3};
        List listC = java.util.Arrays.asList(arrayC);
        System.out.println("listC: " + listC);
    }
}
 Output: 

listA: [a, b, c]
listB: [[I@de6ced]
listC: [1, 2, 3]

Why are int and Integer outputs different?

List into an array

import java.util.*;
public class listToArray{
    public static void main(String args[]){
        List<String> list = new ArrayList<String>();
        String[] array;
        list.add("testA");
        list.add("testB");
        list.add("testC");
        System.out.println("list: " + list);

        String[] strings = new String[list.size()];
        array = list.toArray(strings);
        for(int i = 0, j = array.length; i < j; i++){
            System.out.print(array[i] + ",");
        }
    }
}
 The output is: 
list: [testA, testB, testC]
testA,testB,testC

[remove duplicate data]
Arrays and container transformations can be used to easily remove duplicate array data, although efficiency can be an issue if the array is too large.

import java.util.*;
public class javaArrayUnique{
    public static void main(String args[]){
        String[] array = {"a","b","a","a","c","b"};
        arrayUnique(array);
        //test
        for(int i = 0, j = arrayUnique(array).length; i < j; i++){
            System.out.print(arrayUnique(array)[i] + ",");
        }
    }

    public static String[] arrayUnique(String[] array){
        List<String> list = new ArrayList<String>();
        for(int i = 0, j = array.length; i < j; i++){
            if(!list.contains(array[i])){
                list.add(array[i]);
            }
        }
        String[] strings = new String[list.size()];
        String[] arrayUnique = list.toArray(strings);
        return arrayUnique;
    }
}

  As for efficiency, I did a comparison. An array of 100,000 data running on my computer is about 577ms, while data running a million data is about 5663ms. It also depends on the running power of the computer, but it obviously increases with the size of the array.

import java.util.*;
public class javaArrayUnique{
    public static void main(String args[]){
        Double[] array = new Double[100000];
        for(int i = 0, j = array.length; i < j; i++){
            array[i] = Math.ceil(Math.random()*1000);
        }

        Double[] arrayB = new Double[1000000];
        for(int i = 0, j = arrayB.length; i < j; i++){
            arrayB[i] = Math.ceil(Math.random()*1000);
        }

        System.out.println("start");
        long startTime = System.currentTimeMillis();
        arrayUnique(array);
        long endTime = System.currentTimeMillis();
        System.out.println("array unique run time: " +(endTime - startTime) +"ms");

        long startTimeB = System.currentTimeMillis();
        arrayUnique(arrayB);
        long endTimeB = System.currentTimeMillis();
        System.out.println("arrayB unique run time: " +(endTimeB - startTimeB) +"ms");
    }

    public static Double[] arrayUnique(Double[] array){
        List<Double> list = new ArrayList<Double>();
        for(int i = 0, j = array.length; i < j; i++){
            if(!list.contains(array[i])){
                list.add(array[i]);
            }
        }
        Double[] doubles = new Double[list.size()];
        Double[] arrayUnique = list.toArray(doubles);
        return arrayUnique;
    }
}
 Output: 
start
array unique run time: 577ms
arrayB unique run time: 5663ms


Related articles: