Home  >  Article  >  Java  >  Let’s talk about the definition and use of arrays in Java

Let’s talk about the definition and use of arrays in Java

WBOY
WBOYforward
2022-07-11 12:05:222146browse

This article brings you relevant knowledge about java, which mainly organizes issues related to the definition and use of arrays, including the String array in the main method and the storage of reference data in the array. Let’s take a look at types, array expansion and copying, etc. I hope it will be helpful to everyone.

Let’s talk about the definition and use of arrays in Java

## Recommended study: "

java video tutorial"

One-dimensional array

The

array in Java language is a reference data type; it does not belong to the basic data type; The parent class of the array is Object. An array is actually a container that can hold multiple elements at the same time. (An array is a collection of data)
Array: literally means "a set of data"

Arrays can store data of "basic data types" and data of "reference data types".
Because the array is a reference type, the array object is in the heap memory. (Arrays are stored in the heap)
If the "java object" is stored in the array, what is actually stored is the "reference (memory address) " of the object. In the array Java objects cannot be stored directly (store their addresses).

Once the array is created, it is stipulated in java that the length is immutable. (Array length is immutable) Classification of arrays: one-dimensional array, two-dimensional array, three-dimensional array, multi-dimensional array... (One-dimensional arrays are more common, two-dimensional arrays are occasionally used!)

All array objects have length attribute(java comes with it), which is used to get the number of elements in the array.
Arrays in java require that the types of elements in the array be consistent. For example, an int type array can only store int type, and a Person type array can only store Person type. For example: when shopping in a supermarket, you can only put apples in your shopping bag, not apples and oranges at the same time. (The types of elements stored in the array are uniform) When the array is stored in memory, the memory addresses of the elements in the array (each element stored is arranged next to each other regularly) are continuous. Memory addresses are consecutive. This is the characteristic (feature) of arrays storing elements. Array is actually a simple data structure.
All arrays use the "memory address of the first small box" as the memory address of the entire array object. (The memory address of the first element in the array is used as the memory address of the entire array object.)
Each element in the array has a subscript, and the subscript starts from 0 and increases by 1. The subscript of the last element is: length - 1; the subscript is very important, because when we "access" the elements in the array, we need to use the subscript.

ArrayWhat are the advantages and disadvantages of this data structure?
Advantages: It is extremely efficient when querying/finding/retrieving elements on a certain subscript. It can be said to be the data structure with the highest query efficiency. Why is the retrieval efficiency so high? First:
The memory address of each element is continuous in space storage. Second:
Each element is of the same type, so it takes up the same space. Third:
Know the memory address of the first element, the size of the space occupied by each element, and the subscript, so you can calculate the element above a certain subscript through a mathematical expression memory address. Locate elements directly through memory addresses, so the array retrieval efficiency is the highest. When 100 elements are stored in an array, or 1 million elements are stored, the efficiency is the same in terms of element query/retrieval, because the elements in the array are not searched one by one, but are calculated through mathematical expressions. (Calculate a memory address and locate it directly.)
Disadvantages: First: In order to ensure that the memory address of each element in the array is continuous, the elements are randomly deleted or added to the array. Sometimes, the efficiency is low, because randomly adding and deleting elements will involve the operation of uniform forward or backward displacement of subsequent elements.                   Second: Arrays cannot store large amounts of data, why? Because it is difficult to find a particularly large continuous memory space in the memory space. There is no efficiency impact on the addition or deletion of the last element in the array.

How to declare/define a one-dimensional array?
Syntax format:

int[] array1;
double[] array2;
boolean[] array3;
String[] array4;
Object[] array5;

How to initialize a one-dimensional array?
It includes two methods: static initialization of one-dimensional array and dynamic initialization of one-dimensional array.
        (1) Static initialization syntax format:
            int[] array = {100, 2100, 300, 55};
                                                                   Dynamic initialization of scores:
# int [] array = new int [5]; ## 动 5 here represents the number of elements of array.

          Initialize a 5-length int type array, each element has a default value of 0

         
Another example:
String[] names = new String[6];               6 A String type array of length, with the default value of each element being null.

When to use static array initialization? When to use dynamic array initialization?

(1) When creating a key array, when determining which specific elements are stored in the array, use static initialization

(2) When creating a key array, it is not certain what data will be stored in the future , you can use dynamic initialization to pre-allocate memory space

package com.bjpowernode.javase.array;

public class ArrayTest01 {
    public static void main(String[] args) {
    //1.静态初始化
       int[] a1 = {1,3,5,7,9};
        //所有的数组对象都有length属性,而不是方法!
        System.out.println("数组元素的个数是:"+a1.length);
        //取第一个元素
        System.out.println(a1[0]);
        //取最后一个元素
        System.out.println(a1[a1.length-1]);
        //改数据
        a1[a1.length-1] = 0;
        //遍历数据
        for(int i=0;i< a1.length;i++){
            System.out.println(a1[i]);
        }
        //数据下标越界异常,例如:访问下面为6的数据元素
        //System.out.println(a1[6]);// ArrayIndexOutOfBoundsException


    //2.动态初始化
        int[] a2 = new int[5]; //默认值是0
        for(int i=0;i< a2.length;i++){
            System.out.println(a2[i]);
        }
        //初始化一个Object类型的数组,
          //1.采用静态初始化方式
        Object o1 = new Object();
        Object o2 = new Object();
        Object o3 = new Object();
        Object[] object = {o1,o2,o3};
        //上面就等价于:Object[] object = {new Object(),new Object(),new Object()};
        for(int i=0;i<object.length;i++){
            System.out.println(object[i]);// 默认调用toString方法
        }
          //2.采用动态初始化的方式
        Object[] obj = new Object[3];
        for(int i=0;i<obj.length;i++){
            System.out.println(obj[i]);// null null null
        }

        //初始化一个String类型的数组
          //1.静态初始化
        String[] str1 = {"abc","bcd","cde"};
        for (int i = 0; i < str1.length; i++) {
            System.out.println(str1[i]);
        }
        //2.动态初始化
        String[] str2 = new String[3];
        for (int i = 0; i < str2.length; i++) {
            System.out.println(str2[i]);
        }

    }

}

Dynamic storage memory map

The parameter of the method is an array

When an array is passed, the method also receives it in the form of an array; this array can be static or dynamically created; and we put
The method is written as static, so that

can be called without the need for a new object!

Example 1:

package com.bjpowernode.javase.array;

public class ArrayTest02 {
    //也可以采用C++的风格,写成String args[]
    public static void main(String args[]) {
        System.out.println("HelloWorld");
        // 1.方法的参数传数组---静态初始化方式
        int[] a = {1,2,3,4,5};
        printArray(a);
        // 2.方法的参数传数组---动态初始化方式
        int[] arr = new int[5];
        printArray(arr);
        //   直接一步完成
        printArray(new int[3]);

    }
    //静态方法进行打印
    public static void printArray(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }

}

Example 2: (Master)

(1)一Pass a static array in a special case; if you pass a static array directly, the syntax must be written like this!

(2) Let’s look at an example first:

int[] arr = {1,2,3}

;When we pass the parameters of the array, we usually pass the array name arr, for example: printArray(arr); But another way is to pass it and remove the remaining components of the array name arr: int[]{1,2,3}, but add new keyword, for example:

printArray(new int[]{1,2,3})

;

package com.bjpowernode.javase.array;

public class ArrayTest03 {
    public static void main(String[] args) {
     //----------1.动态初始化一位数组(两种传参方式)
        //第一种传参方式
        int[] a1 = new int[5];//默认是5个0
        printArray(a1);
        System.out.println("-------------");
        //第二种传参方式
        printArray(new int[3]);
        System.out.println("-------------");
     //----------2.静态初始化一位数组(两种传参方式)
        //第一种传参方式
        int[] a2 = {1,2,3};
        printArray(a2);
        System.out.println("-------------");
        //第二种传参方式----直接传递一个静态数组
        printArray(new int[]{4,5,6});

    }
    //调用的静态方法----静态方法比较方便,不需要new对象
    public static void printArray(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

String array in main method

(1) For main(String[] args); analyze: who is responsible for calling the main method (JVM)

When the JVM calls the main method, it will automatically pass a String array Come over here, the length is 0.

Example 1:

package com.bjpowernode.javase.array;

public class ArrayTest04 {
    // 这个方法程序员负责写出来,JVM负责调用。JVM调用的时候一定会传一个String数组过来。
    public static void main(String[] args) {
        // JVM默认传递过来的这个数组对象的长度?默认是0
        // 通过测试得出:args不是null。
        System.out.println("JVM给传递过来的String数组参数,它这个数组的长度是?"
        + args.length); //0

        // 以下这一行代码表示的含义:数组对象创建了,但是数组中没有任何数据。就等价于:
        String[] strs = new String[0]; //动态的方式
        //String[] strs = {}; // 静态初始化数组,里面没东西。
        printLength(strs); //调用printLength静态方法

/*
     既然传过来的“String[] args”数组里什么都没有;那么这个数组什么时候里面会有值呢?
     其实这个数组是留给用户的,用户可以在控制台上输入参数,这个参数自动会被转换为“String[] args”
     例如这样运行程序:java ArrayTest04 abc def xyz;相当于在编译时进行传参
     那么这个时候JVM会自动将“abc def xyz”通过空格的方式进行分离,分离完成之后,自动放到“String[] args”数组当中。
     所以main方法上面的String[] args数组主要是用来接收用户输入参数的。
     把abc def xyz 转换成字符串数组:{"abc","def","xyz"}
*/
        // 遍历数组
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
        //既然是编译时进行传参,对于编译运行一体的IDEA怎么使用呢?
        //Run--->EditConfiguration--->Program Arguments里面进行传参,然后在从后重新运行

    }

    public static void printLength(String[] args){
        System.out.println(args.length); // 0
    }
}
Example 2:

(1) main What is the use of "String[] args" above the method?

Can be used to simulate a login system

! Please take a look at the following interesting example:

package com.bjpowernode.javase.array;
/*
   模拟一个系统,假设这个系统要使用,必须输入用户名和密码。
*/
public class ArrayTest05 {
    public static void main(String[] args) {
        //先判断长度,是不是两个字符串长度,不是2直接终止程序
        if(args.length != 2){
            System.out.println("请输入用户名和密码");
            return;
        }

        //取出用户名和密码
        String username = args[0];
        String password = args[1];
        // 假设用户名是admin,密码是123的时候表示登录成功。其它一律失败。
        // 判断两个字符串是否相等,需要使用equals方法。
        // if(username.equals("admin") && password.equals("123")){ //这样有可能空指针异常
        // 下面这种编写方式,也可以避免空该指针异常!
        if("admin".equals(username) && "123".equals(password)){ 
            System.out.println("恭喜你,登录成功");
            System.out.println("您可以继续使用该系统");
        }else{
            System.out.println("账户或密码错误,请重新输入");
        }
    }
}

Storing reference data types in arrays (key points)

(1) In-depth analysis of one-dimensional arrays : The type stored in the array is:
Reference data type

; for arrays, actually only the "memory address" of the Java object can be stored. Each element stored in the array is a "reference" . The following example question focuses on understanding! (2)

Arrays require the elements in the array to be of the same type; but

can also store its subtypes!

package com.bjpowernode.javase.array;
public class ArrayTest06 {
    public static void main(String[] args) {
        //1.静态创建一个Animal类型的数组
        Animal a1 = new Animal();
        Animal a2 = new Animal();
        Animal[] animals = {a1,a2};

        //对Animal数组进行遍历
        for (int i = 0; i < animals.length; i++) {
            //方法1
            /*Animal a = animals[i];
            a.move();*/
            //方法2
            animals[i].move();
        }

        //2.动态初始化一个长度为2的animal类型的数组
        Animal[] ans = new Animal[2];
        ans[0] = new Animal();
        //ans[1] = new Product(); //err,Product和Animals没有任何关系
        //Animal数组中只能存放Animal类型,不能存放Product类型

        //3.Animal数组中可以存放Cat类型的数据,因为Cat是Animal一个子类
       ans[1] = new Cat();
        for (int j = 0; j < ans.length; j++) {
            ans[j].move();
        }

        //4.创建一个Animal类型的数据,数组当中存储Cat和Bird
          //4.1静态创建
        Cat cat = new Cat();
        Bird bird = new Bird();
        Animal[] anim = {cat,bird};
        for (int i = 0; i < anim.length; i++) {
            //直接调用子类和父类都有的move()方法
            //anim[i].move();
            
            //这里想要调用子类Bird里面特有的方法,需要向下转型
            if(anim[i] instanceof Bird){
                Bird b = (Bird)anim[i]; //向下转型
                b.move();
                b.sing(); //调用子类特有的方法
            }else{
                anim[i].move();
            }

        }


    }
}
//动物类
class Animal{
    public void move(){
        System.out.println("Animals move.....");
    }
}
//商品类
class Product{

}

//有一个猫类继承动物类
class Cat extends Animal{
    public void move(){
        System.out.println("Cat move.....");
    }
}

//有一个鸟类继承动物类
class Bird extends Animal{
    public void move(){
        System.out.println("Bird move.....");
    }

    //鸟特有的方法
    public void sing(){
        System.out.println("鸟儿在歌唱!");
    }
}
Array expansion and copy

In Java development, once the array length is determined to be immutable, what should I do if the array is full and needs to be expanded?
(1) The expansion of

arrays in java
is: First create a large-capacity array, and then copy the elements in the small-capacity array to the large array one by one. The small capacity will released. (2) Conclusion: Array expansion efficiency is low
. Because it involves copying issues. So please pay attention in future development: copy the array as little as possible. You can estimate the appropriate length below when creating an array object. It is best to estimate accurately, which can reduce the number of array expansions. Improve efficiency. (3)

Use

System.arraycopy to copy , a total of 5 parameters; System.arraycopy(source array, subscript, destination array, subscript, Number of copies to be copied)

package com.bjpowernode.javase.array;
public class ArrayTest07 {
    public static void main(String[] args) {
        //java中的数组是怎样拷贝的呢?System.arraycopy(5个参数)
        //System.arraycopy(源,下标,目的地,下标,个数)

        //拷贝源---把3、5、7拷贝过去
        int[] src = {1,3,5,7,9};
        //拷贝目的地---拷贝到下标为5的地方
        int[] dest = new int[20];
        //调用拷贝函数
        System.arraycopy(src,1,dest,5,3);
        //打印验证
        for (int i = 0; i < dest.length; i++) {
            System.out.println(dest[i]+" ");
        }

        //拷贝引用数据类型
        String[] str = {"hello","world"};
        String[] strs = new String[10];
        System.arraycopy(str,0,strs,3,2);
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        System.out.println("--------------");
        
        //采用动态开辟的时候拷贝的是地址
        Object[] objs = {new Object(),new Object(),new Object()};
        Object[] objects = new Object[5];
        System.arraycopy(objs,0,objects,0,3);
        for (int i = 0; i < objects.length; i++) {
            System.out.println(objects[i]);

        }

    }
}

内存图

推荐学习:《java视频教程

The above is the detailed content of Let’s talk about the definition and use of arrays in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete