Java数组

首先必须声明数组变量,才能在程序中使用数组

实例:

dataType[] arrayRefVar; // 首选的方法

dataType arrayRefVar[]; // 效果相同,但不是首选方法

Java语言使用new操作符来创建数组

arrayRefVar = new dataType[arraySize];

数组的元素类型和数组的大小都是确定的

如何创建、初始化和操纵数组:实例:

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); } }

数组作为函数的参数

public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }

数组作为函数的返回值

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; }

多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一维数组,其每一个元素都是一个一维数组

 

posted on 2019-04-03 09:00  里里零  阅读(257)  评论(0编辑  收藏  举报

导航