Home >Java >javaTutorial >Array of Java learning summary (organized and shared)

Array of Java learning summary (organized and shared)

WBOY
WBOYforward
2022-04-01 12:01:332693browse

This article brings you relevant knowledge about java, which mainly introduces related issues about arrays, including why to use arrays, the definition of arrays, the initialization of arrays, and the functions of arrays. Basic operations, etc. I hope it will be helpful to everyone.

Array of Java learning summary (organized and shared)

Recommended study: "java tutorial"

1. Why to use arrays and the definition of arrays

1.1 Why use arrays

Question 1:

When declaring variables, each individual variable must correspond to a variable name, but now when we need to process a group of data of the same type, If you want to represent the ages of 100 people in the class, and you definitely don't want to define 100 variables to represent everyone's age, what should you do? Consider the following examples again.

int age = 17;//Indicates an age

Question 2:

To find the sum of two numbers, you need a method. To find the sum of 5 numbers, you need Overload a method to find the sum of 100 numbers, the sum of 1000 numbers, and the sum of 10000 numbers. The parameter list of the method will be very long, and there will be many methods, and you will have to remember which method is Which method has two parameters and which method has three parameters. This always feels very unpleasant. If you analyze this function carefully, it is actually just to find the sum of a set of values. This method does not care about the specific number of addends, it only cares about which numbers need to be added up.

Master’s advice: When defining formal parameters of a method, it is best not to exceed 5.

1.2 What is an array

Simply put, it is a set of data, a pile of data. The so-called array is a data form in which several variables of the same type are organized in an orderly manner for the convenience of processing in programming. These A collection of data of the same type arranged in a certain order is called an array. Each data in the array is called an array element. The elements in the array are indexed to indicate their storage location. The index starts from 0 and the step size is 1. It is a bit like the row number of an Excel table increasing row by row.

1.3 Definition of array

Method 1 (

recommended to use): Type of array element[] Array name; Method 2: Type of array element Array name[];

eg: int ages[];

Note:Arrays must be initialized before they can be used. Because initialization means allocating space in memory.

2. Initialization of arrays       Arrays in Java must be initialized before they can be used,

The so-called initialization is to allocate memory to the array elements and assign memory to each element Assign initial value.

             The two ways to initialize the array are divided into static initialization, dynamic initialization

; no matter which way the array is initializedOnce initialization is completed, the length of the array is fixed unless reinitialized. In other words, the array is of fixed length.          Arrays are fixed-length: Once the array is initialized successfully, the number of elements in the array is fixed and cannot be changed. If changes are needed, they can only be re-initialized. 2.1 Static initialization of arrays

It is up to us to set the initialization value for each array element, and the length of the array is determined by the system (JVM).

Syntax:

Array element type [] Array name =

new

Array element type []{element 1, element 2, element 3,...};Example:

int[] nums = new int[]{1,3,5,7,9};

Simple writing method, must be initialized immediately after declaration, cannot be declared first and then initialized; int[] nums = {1,3,5,7,9};

Illustration of the static initialization operation and reassignment operation of the array

##2.2 Dynamic initialization of the array

It is up to us to set the array The number of

elements (array length), and the initial value of each array element is determined by the system.

Syntax:

Array element type[] Array name = new Array element type[length ];

Example:

    int[] ages = new  int[
100
];

Note:

int[] nums = new int[5]{1,3,5, 7,9};//The writing is wrong. Static initialization and dynamic initialization cannot be used at the same time.

2.3 When to use static initialization and when to use dynamic initialization?

When we

know in advance what data needs to be stored, choose static initialization;

When we

don’t know in advance what data needs to be stored, we can only use dynamic initialization;

In Java, the initial value is set for the data type, as shown below:

0##longfloatdouble##booleancharReference data type

Data type

Initial value

##byte, short, int

0L

0F

##0.0D

false

'\ u0000' (meaning empty)

null

三、数组基本操作(一维数组)

3.1 数组基本操作:

  • 获取元素: 元素类型 变量 =  数组名[index];
  • 设置元素: 数组名[index] = 值;
  • 遍历数组元素: 建议使用for循环,因为for循环事先知道循环的次数
  • 数组长度int len = 数组名.length;  length是属性,不是方法.
  • 索引范围:  从0开始,逐一递增。  [0,数组名.length-1]

3.2 操作数组常见异常:

NullPointerException:空指针异常(空引用)。

出现该异常的原因:当数组还未初始化,就直接操作数组

如以下代码:

String[] bs = null;

System.out.println(bs.length)

ArrayIndexOutOfBoundsException:数组的索引越界异常。

出现该异常的原因:根据索引取出数据元素时,输入了超出数组索引范围之外的值。

如下代码:

int[] nums = {1,3,5,7,9};

int a = nums[4];

3.3 获取数组最大最小元素

/**
 * 求数组最大值
 *
 * @param nums
 * @return
 */
public static int getMax(int[] nums) {
    int result = 0;
    for (int i = 0; i 9c7b11bfa3ff5f0940b8ea5c0821c84e num) {
            result = num;
        }
    }
    return result;
}

3.4 打印数组元素

        当我们直接使用System.out.println()打印数组的时候,打印出来是hashCode值,如

int[] nums = new int[]{1, 3, 5, 7, 9};

System.out.println(nums);

我们不喜欢,我们想打印数组的时候,把该数组的元素打印出来,这时需要循环遍历打印

int[] nums = new int[]{1, 3, 5, 7, 9};
for (int i = 0; i 3f40d6801d52824bc5cc39707ea4ab57= 0; i--) {
        result[index] = nums[i];
        index++;
    }
    return result;
}

3.6 线性搜索:元素出现索引(第一次/最后一次)

        数组的线性搜索指得就是挨个遍历,查找数组中与key相同的元素,若查找不到则可以返回-1(惯例,自定义),其效率为O(n)。

例子:int[] arr = {10,20,30,10,50,-30,10};获取元素10在arr数组中第一次出现的索引和最后一次出现的索引

/**
 * 获取数组中指定元素第一次出现的索引
 *
 * @param nums
 * @param element
 * @return
 */
public static int indexOf(int[] nums, int element) {
    for (int i = 0; i ed78c9b2c0c5a5caec46ff34a5fe5ba5= 0; i--) {
        if (element == nums[i]) {
            return i;
        }
    }
    return -1;
}

四、多维数组

        在前面的文章中我们有提到数组其实就是是多个数据的集合。如果现在有多个数组,我想把多个数组保存在一个集合中,此时我又应该如何完成呢?此时就需要引入多维数组的概念。多维数组其实就是把整个数组看成一个元素,存放到另一个数组当中去

多维数组的语法:

数组元素类型[] 数组名;

例如如下定义二维数组的格式

int[][]  arr = new int[][]   {

  arr1 ,arr2,arr3

};

int[][]  arr = new int[][]   {

  {1,2,3} ,

  {4,5},

  {6}

};

4.1 多维数组和一维数组的区别

  • 一维数组:数组中的每一个元素都是一个值(基本类型和引用类型的值);
  • 二维数组:数组中的每一个元素又是一个一位数组;
  • 三维数组:数组中的每一个元素又是一个二维数组;

注意:严格上说在Java中不存在多维数组的概念。为了和C语言做区分一般称之为数组中的数组

4.2 二维数组的初始化操作

静态初始化

int[][]  arr = new int[][]   {

  {1,2,3} ,

  {4,5},

  {6}

};

动态初始化

 int[][]  arr = new int[3][5] ;//创建一个长度为3的二维数组,每一个元素(一维数组)的长度为5。

针对于N维数组,需要N个循环嵌套。

五、Java5对数组的新语法支持

        Java5对数组的新语法支持主要是增强for循环(foreach)方法的可变参数

5.1 增强for循环-foreach

在之前我们使用for循环的打印元素操作如下

int[] nums = new int[]{1, 3, 5, 7, 9};
for (int i = 0; i fc94e68f7aa2711b3ffbc52bdc58654b语法糖。<p><strong>注意</strong>:语法糖的最大甜头就是让开发者写更少、更简单的代码,完成相同的功能。<span style="color:#4da8ee;"><strong>当我们在迭代数组元素的时候不关心数组的索引的时,首选使用foreach</strong></span>。当然咯,foreach远远没有本篇博客讲解的这么简单,星仔到时候带着大家在集合框架篇的时候再深入讲解foreach。</p><p style="text-align:center;"><img alt="" src="https://img.php.cn/upload/article/000/000/067/b9c206b202be8e9cc09cbc7b102a4161-37.png"></p><h2 id="5.2%20%E6%96%B9%E6%B3%95%E7%9A%84%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0">5.2 方法的可变参数</h2><p><strong>Java5的时候为什么要增加可变参数呢?我们来看一下以下的需求</strong></p><p>需求:编写一个方法,统计使用数组传递过来的总和。</p><p><img alt="" src="https://img.php.cn/upload/article/000/000/067/0ab0ceca8f5fec17090a4aca68d9e560-39.png"></p><p><strong>虽然说也是可以实现,但是我们心里肯定是不爽的,主要在于以下几点:</strong></p>
  • 为了求多个数之和,我们还得先创建一个数组来存储数据。
  • 如果多个数是变化的,比如求3个数之和变成求5个数之和.......,还得去修改定义数组,但是数组是定长的。

那如果要解决该问题该怎么办呢?这个时候就需要引入Java5的另一个新特性:方法的可变参数(说的是参数的个数可变)

注意:

  • 方法的可变参数其实也是一个语法糖,是编译器级别的新特性。主要是为了让开发者写代码更简单。
  • 方法的可变参数其底层是就是一个数组类型
  • 可变参数必须作为方法的最后一个参数,避免参数的歧义性。
  • 一个方法最多只有一个可变参数

六、数组元素拷贝

数组拷贝:从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

  • 从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。
  • 被复制的组件的编号等于 length 参数。
  • 源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。

数组拷贝操作是经常使用到的,SUN就直接把数组的拷贝操作存放在JDK中的System类中

Object:Java语言中的根类。是所有类的老祖宗。Object可以表示任意数据类型。

该方法没有方法体,该方法使用了native修饰符(本地方法)。该方法底层使用了C/C++语言实现了,Java直接调用其他语言编写好的功能

arraycopy 方法使用方式

System.arraycopy(src, 2, dest, 5, 4);

查阅API文档了(Java的帮助文档/好比字典),在什么类中有什么功能的方法即可。文档在手,天下我有!

推荐学习:《java学习教程

The above is the detailed content of Array of Java learning summary (organized and shared). 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