Home > Java > javaTutorial > body text

Basic operations on Java arrays

WBOY
Release: 2023-04-25 21:01:05
forward
1061 people have browsed it

Basic operations on Java arrays


1. Why 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 set of the same type of data, if we want to express the ages of 100 people in the class, we absolutely do not want to Define 100 variables to represent the age of each person, what should we 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 speaking, it is a set of data, a pile of data. The so-called array is a data form that organizes several variables of the same type in an ordered form 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.

Basic operations on Java arrays

1.3 Definition of array

Method 1 (recommended): Type of array element[] Array name; eg: int [] ages;

Int[] can be regarded as a data type, an array type of int type.

Method 2: Type of array element Array name[];       eg: int ages[];

Note: The array must be initialized before it 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 an initial value to each element.

The two ways to initialize an array are divided into static initialization and dynamic initialization; no matter which way the array is initializedOnce the initialization is completed, the length of the array is fixed unless it is re-initialized. . In other words, the array is of fixed length .

The array is of 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

We set the initialization value for each array element ourselves, 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, it must be initialized immediately after declaration, and cannot be initialized after declaration; int[] nums = {1,3,5,7,9};

Illustration of array static initialization operation and reassignment operation

Basic operations on Java arrays

2.2 Dynamic initialization of the array

We set the number of elements (array length) of the array, 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
];
Copy after login

Note: int[] nums = new int[5]{1,3,5,7,9};/ / is written incorrectly. 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, we need When storing data, you can only usedynamic initialization;

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

0Fboolean##charReference data type

Data type

##Initial value

byte, short, int

0

long

0L

##float

double

##0.0D

false

'\u0000' (indicates 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)
Copy after login

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

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

如下代码:

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

int a = nums[4];
Copy after login

3.3 获取数组最大最小元素

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

/**
 * 求数据最小值
 *
 * @param nums
 * @return
 */
public static int getMin(int[] nums) {
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        int num = nums[i];
        if (i == 0) {
            result = num;
        }
        if (result > num) {
            result = num;
        }
    }
    return result;
}
Copy after login

3.4 打印数组元素

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

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

System.out.println(nums);
Copy after login

Basic operations on Java arrays

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

int[] nums = new int[]{1, 3, 5, 7, 9};
for (int i = 0; i < nums.length; i++) {
    System.out.print(nums[i] + " ");
}
Copy after login

但是呢,每次想打印数据中的元素都还要循环遍历一遍,好麻烦啊! 有没有更好的方式呢?其实不用着急,Java前辈们已经帮我们想到了这一点了,我们只需要调用Arrays.toString()方法就能够对数组进行打印

3.5 逆序排列数组元素

例子:原数组[A, B, C, D, E],要求对该数组进行逆序操作得到新数组:[E, D, C, B, A]。

public static String[] reversedOrder(String[] nums) {
    String[] result = new String[nums.length];
    int index = 0;
    for (int i = nums.length - 1; i >= 0; i--) {
        result[index] = nums[i];
        index++;
    }
    return result;
}
Copy after login

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 < nums.length; i++) {
        if (element == nums[i]) {
            return i;
        }
    }
    return -1;
}

/**
 * 获取数组中指定元素最后一次出现的索引
 *
 * @param nums
 * @param element
 * @return
 */
public static int lastIndexOf(int[] nums, int element) {
    for (int i = nums.length - 1; i >= 0; i--) {
        if (element == nums[i]) {
            return i;
        }
    }
    return -1;
}
Copy after login

四、多维数组

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

多维数组的语法:

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

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

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

  arr1 ,arr2,arr3

};

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

  {1,2,3} ,

  {4,5},

  {6}

};
Copy after login

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个循环嵌套。

Basic operations on Java arrays

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

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

5.1 增强for循环-foreach

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

int[] nums = new int[]{1, 3, 5, 7, 9};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}
Copy after login

其实我们在使用循环迭代数组的时候,往往是不关心迭代变量(数组的索引)。那在Java中有没有更好的方式,在迭代数组元素的时候就只操作数组元素,不去操作数组的索引呢?其实是有的。

从Java5开始(JDK1.5)开始,Java提供了一种新的语法:增强for循环(foreach)。

语法:

for(数组元素类型 变量 : 数组名)

{

循环体

}

我们通过反编译工具查看字节码,会发现foreach其实在底层依然是使用for循环+索引来操作数组的。我们把增强for循环称之为编译器的新特性---->语法糖

注意:语法糖的最大甜头就是让开发者写更少、更简单的代码,完成相同的功能。当我们在迭代数组元素的时候不关心数组的索引的时,首选使用foreach。当然咯,foreach远远没有本篇博客讲解的这么简单,星仔到时候带着大家在集合框架篇的时候再深入讲解foreach。

Basic operations on Java arrays

5.2 方法的可变参数

Java5的时候为什么要增加可变参数呢?我们来看一下以下的需求

需求:编写一个方法,统计使用数组传递过来的总和。

Basic operations on Java arrays

虽然说也是可以实现,但是我们心里肯定是不爽的,主要在于以下几点:

  • 为了求多个数之和,我们还得先创建一个数组来存储数据。

  • 如果多个数是变化的,比如求3个数之和变成求5个数之和.......,还得去修改定义数组,但是数组是定长的。

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

注意:

  • 方法的可变参数其实也是一个语法糖,是编译器级别的新特性。主要是为了让开发者写代码更简单。

  • 方法的可变参数其底层是就是一个数组类型

  • 可变参数必须作为方法的最后一个参数,避免参数的歧义性。

  • 一个方法最多只有一个可变参数

Basic operations on Java arrays

六、数组元素拷贝

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

  • 从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。

  • 被复制的组件的编号等于 length 参数。

  • 源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。

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

Basic operations on Java arrays

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

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

arraycopy 方法使用方式

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

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

Basic operations on Java arrays


The above is the detailed content of Basic operations on Java arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template