Java 数组
1 概述
概念
Java 语言中提供的数组是用来存储固定大小的同类型元素。
数组声明
1 2
| dataType[] arrayRefVar; dataType arrayRefVar[];
|
数组定义
- 使用new关键字和数组的大小创建数组。数组中的每一个元素都使用默认初始化。基本类型被初始化位数值,引用类型被初始化位空。
- 使用花括号和数组中的元素,创建数组
1 2
| dataType[] arrayRefVar = new dataType[arraySize]; dataType[] arrayRefVar = {value0, value1, ..., valuek};
|
数组遍历
数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本循环或者 For-Each 循环。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
|
1 2 3 4 5 6 7 8 9 10
| public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // 打印所有数组元素 for (double element: myList) { System.out.println(element); } } }
|
数组参数
数组可以作为参数传递给方法,本质是,数组是引用类型的变量的一种,所以传递的是数组的地址。
1 2 3 4 5
| public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }
|
数组返回值
1 2 3 4 5 6 7 8
| public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; }
|
多维数组
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一维数组,其每一个元素都是一个一维数组,
- 可以直接固定每一维的数组长度
1 2
| String[][] str = new String[3][4]; int[][] a = new int[2][3];
|
- 可以逐步分配每一维数组的长度
1 2 3 4 5 6 7 8
| String[][] s = new String[2][]; s[0] = new String[2]; s[1] = new String[3]; s[0][0] = new String("Good"); s[0][1] = new String("Luck"); s[1][0] = new String("to"); s[1][1] = new String("you"); s[1][2] = new String("!");
|