search
HomeJavajavaTutorialJava Improvement Chapter (18)-----Array One: Understanding JAVA Arrays

Oh, it understood. The river is neither as shallow as Uncle Cow said, nor as deep as the little squirrel said. You can only know if you try it yourself! Hearsay can always only show the phenomenon. Only by trying it yourself can you know the depth of it! ! ! ! !

1. What is an array

Array? What is an array? In my mind, arrays should be like this: create and assemble them through the new keyword, access its elements by using integer index values, and its size is immutable!

           But this is only the most superficial thing of the array! Deeper? That's it: an array is a simple composite data type. It is a collection of ordered data. Each data in it has the same data type. We uniquely use the array name plus a subscript value that will not go out of bounds. Determine the elements in the array.

          There is something deeper, that is, the array is a special object! ! (I don’t understand this LZ very well, and I haven’t read JVM, so my insights are limited). The following references: http://www.php.cn/, http://www.php.cn/

##           Regardless of whether arrays are used in other languages What, in java it is an object. A rather special object.

public class Test {
    public static void main(String[] args) {
        int[] array = new int[10];
        System.out.println("array的父类是:" + array.getClass().getSuperclass());
        System.out.println("array的类名是:" + array.getClass().getName());
    }
}
-------Output:
array的父类是:class java.lang.Object
array的类名是:[I

As can be seen from the above example, the array is a direct subclass of Object, which belongs to " "First Class Object", but it is very different from ordinary Java objects. It can be seen from its class name: [I, what is this? ? I didn't find this class in the JDK. It is said that this "[I" is not a legal identifier. How to define it as a category? So I think the geniuses at SUM must have done special processing on the bottom layer of the array.

          Let’s look at the following example:

public class Test {
    public static void main(String[] args) {
        int[] array_00 = new int[10];
        System.out.println("一维数组:" + array_00.getClass().getName());
        int[][] array_01 = new int[10][10];
        System.out.println("二维数组:" + array_01.getClass().getName());
        
        int[][][] array_02 = new int[10][10][10];
        System.out.println("三维数组:" + array_02.getClass().getName());
    }
}
-----------------Output:
一维数组:[I
二维数组:[[I
三维数组:[[[I

       Through this example we know: [ represents the dimension of the array, one [ represents one dimension, and two [ represents two dimensions. It can simply be said that the class name of an array consists of several '['s and the internal name of the array element type. If it’s not clear, let’s look at it again:

public class Test {
    public static void main(String[] args) {
        System.out.println("Object[]:" + Object[].class);
        System.out.println("Object[][]:" + Object[][].class);
        System.err.println("Object[][][]:" + Object[][][].class);
        System.out.println("Object:" + Object.class);
    }
}
---------Output:
Object[]:class [Ljava.lang.Object;
Object[][]:class [[Ljava.lang.Object;
Object[][][]:class [[[Ljava.lang.Object;
Object:class java.lang.Object

              From this example we can see the "true face of Mount Lu" of the array . At the same time, it can also be seen that arrays are different from ordinary Java classes. Ordinary Java classes use fully qualified path names + class names as their only identifiers, while arrays use several [+L+array element class full names. Define the path + class to uniquely identify it. This difference may explain to some extent that there is a big difference in the implementation of arrays and ordinary Java classes. Perhaps this difference can be used to make the JVM distinguish between arrays and ordinary Java classes.

## No matter what this [i Dongdong, who is declared from what is the stuff? Can confirm: this is determined at runtime). Take a look at the following first:

##

public class Test {
    public static void main(String[] args) {
        int[] array = new int[10];
        Class clazz = array.getClass();   
        System.out.println(clazz.getDeclaredFields().length);   
        System.out.println(clazz.getDeclaredMethods().length);   
        System.out.println(clazz.getDeclaredConstructors().length);   
        System.out.println(clazz.getDeclaredAnnotations().length);   
        System.out.println(clazz.getDeclaredClasses().length);   
    }
}
----------------Output:
0
0
0
0
0

                                                                                                                                              There are no member variables, member methods, constructors, Annotations or even the length member variable. It is a completely empty class. Length is not declared, so why doesn't the compiler report an error when we array.length? Indeed, the length of an array is a very special member variable. We know that the array is the direct class of Object, but Object does not have the member variable length, so length should be the member variable of the array, but from the above example, we find that the array does not have any member variables at all. Isn't it contradictory?

public class Main {
    public static void main(String[] args) {
        int a[] = new int[2];
        int i = a.length;
    }
}

Open the class file and get the bytecode of the main method:

0 iconst_2                   //将int型常量2压入操作数栈  
    1 newarray 10 (int)          //将2弹出操作数栈,作为长度,创建一个元素类型为int, 维度为1的数组,并将数组的引用压入操作数栈  
    3 astore_1                   //将数组的引用从操作数栈中弹出,保存在索引为1的局部变量(即a)中  
    4 aload_1                    //将索引为1的局部变量(即a)压入操作数栈  
    5 arraylength                //从操作数栈弹出数组引用(即a),并获取其长度(JVM负责实现如何获取),并将长度压入操作数栈  
    6 istore_2                   //将数组长度从操作数栈弹出,保存在索引为2的局部变量(即i)中  
    7 return                     //main方法返回

       在这个字节码中我们还是没有看到length这个成员变量,但是看到了这个:arraylength ,这条指令是用来获取数组的长度的,所以说JVM对数组的长度做了特殊的处理,它是通过arraylength这条指令来实现的。

       二、数组的使用方法

       通过上面算是对数组是什么有了一个初步的认识,下面将简单介绍数组的使用方法。

       数组的使用方法无非就是四个步骤:声明数组、分配空间、赋值、处理。

       声明数组:就是告诉计算机数组的类型是什么。有两种形式:int[] array、int array[]。

       分配空间:告诉计算机需要给该数组分配多少连续的空间,记住是连续的。array = new int[10];

       赋值:赋值就是在已经分配的空间里面放入数据。array[0] = 1 、array[1] = 2……其实分配空间和赋值是一起进行的,也就是完成数组的初始化。有如下三种形式:

int a[] = new int[2];    //默认为0,如果是引用数据类型就为null
        int b[] = new int[] {1,2,3,4,5};    
        int c[] = {1,2,3,4,5};

       处理:就是对数组元素进行操作。通过数组名+有效的下标来确认数据。

以上就是java提高篇(十八)-----数组之一:认识JAVA数组 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment