数组

茴香豆 Lv5

数组是相同类型数据的有序集合。

数组的声明与创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.hui.t4;

public class Demo01 {
public static void main(String[] args) {
// 变量的类型 变量的名字 = 变量的值
int[] nums; // 1. 定义 首选
int nums2[]; // 不建议

// 使用new array操作创建数组
nums = new int[10]; // 2. 创建一个数组这里面可以存放10个int类型的数字

// 简便定义
int[] nums3 = new int[10];

// 3. 给数组元素赋值
nums[0] = 10;
// 求和
int sum = 0;
for (int i = 0; i < nums.length; i++){
sum += nums[i];
}
System.out.println(sum);
}
}

数组的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.hui.t4;

public class Demo02 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5};
// 没有下标
for (int array : arrays){
System.out.println(array);
}
printArray(arrays);
int[] reverse = reverse(arrays);
printArray(reverse);
}
// 数组作为参数
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++){
System.out.println(i + ":" + arrays[i]);
}
}
// 数组作为返回值
public static int[] reverse(int[] arrays){
int[] result = new int[arrays.length];
for(int i = 0; i < arrays.length; i++){
result[arrays.length-i-1] = arrays[i];
}
return result;
}
}

二维数组

1
int[][] arrays = new int[3][5];

Arrays类讲解

可以直接使用类名调用,常用功能:

  • 赋值:fill
  • 排序:sort
  • 比较:equal
  • 查找:binarySearch
  • Title: 数组
  • Author: 茴香豆
  • Created at : 2024-06-02 10:43:37
  • Updated at : 2024-06-02 11:18:34
  • Link: https://hxiangdou.github.io/2024/06/02/Java-4/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments