【Java基础知识14讲-07:Java数组】
数组是相同类型的数据按顺序组成的⼀种复合数据类型。
如果在程序中想定义多个同样类型的。变量,数组是⼀个很好的⽅法
数组是⼀组相关数据的集合,可以分为⼀维数组,⼆维数组和多维数组。
一:声明数组
声明数组包括数组的名字,数组包含的元素的数据类型
声明⼀维数组有下列两种格式:
1.数组元素类型数组名字[];
2.数组元素类型[] 数组名字;
例如:
int array1[];
int[] array2
;
二:创建数组
声明数组仅仅是给出了数组名和元素的数据类型
要想使⽤数组必须为它分配内存空间,即创建数组
在为数组分配内存空间时必须指明数组的长度
数组名字= new 数组元素的类型[数组元素的个数];
声明数组包括数组的名字,数组包含的元素的数据类型
创建数组时需要指明数组的长度
例如:
array1 = new int[4];
可以同时创建和声明:
int[] array3 = new int[10];
三:数组的使⽤
数组通过下标访问⾃⼰的元素,如boy[0], boy[1]等。
注意下标的范围,如果数组长度为n,则范围是0 ~ n-1
数组的初始化
int score = new int[3];
score[0] = 98;
score[1] = 96;
score[2] = 100;
也可以:
int[] score = {98, 96, 100};
多维数组
数组中的元素也可以是数组,即多维数组
int[][] measure =new int[2][3];
类似于矩阵,2⾏3列
访问
measure[1][0], measure[0][2]
数组程序举例如下:
public class arrayTest {
public static void main(String[] arrgs) {
int [] score = new int [5];
score [0] = 95;
score [1] = 83;
score [2] = 90;
score [3] = 100;
score [4] = 99;
System.out.println("score [0] is " + score [0]);
System.out.println("score [3] is " + score [3]);
//另一种方法初始化数组
int[] temp = {37,32,5,6};
System.out.println("temp[2] is " + temp[2]);
//做运算
int result = score[4] + temp[3]; //99+6=105
System.out.println("result is " + result);
//定义一个二维数组
int[][] two = new int[3][2];
two[0][0] = 0;
two[0][1] = 1;
two[1][0] = 2;
two[1][1] = 3;
two[2][0] = 4;
two[2][1] = two[0][0] + two[1][0] ; //0+2 =2
System.out.println("two[2][1] is " + two[2][1]); //2
//另一种初始化方法
int[][] location = {{1,2,3},{4,5,6}};
System.out.println("location[1][1] is " + location[1][1]); //5
}
}
在IED中运行结果如下: