Array
本章节将介绍Java 引用数据类型: 数组
数组的声明, 初始化, 遍历
数组的声明形式: 数据类型名[ ] 数组名 = new 数据类型名[数组长度]
// 声明并创建一个整形数组
int[] intArray = new int[5];// 默认初始值为0
// 声明并创建一个float串数组
float[] floatArray = new float[5];// 默认初始值为0
类型数据可以为基础数据类型int, long, float, double, char, boolean, 也可以为引用数据类型, 比如String
// 声明并创建一个字符串数组
String[] strArray = new String[10];// 默认初始值为null
数组也可以在声明时进行初始化,格式: 数据类型名[ ] 数组名={元素1, 元素2, ..., 元素n}
// 初始化字符数组
char[] ch = { 'a', 'b', 'c', 'd' };
可以使用索引遍历数组, 数组支持索引访问, 也支持.length()方法
//使用索引遍历数组
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]+" ");
}
也使用可以增强型for循环遍历
//增强型for循环输出数组ch
for (char c:ch) {
System.out.print(c+" ");
}
二维数组
二维数组声明 : 类型 [][] 变量名=new 类型名[行数][列数], 行数必须有,列数可以不提供
// 创建一个三行三列的int数组
int[][] intArray = new int[3][3];
创建float类型的数组时候,只指定行数
// 必须要指定行数,列数可以省略
float[][] floatArray = new float[3][];
// 每一行相当于一个一维数组
floatArray[0] = new float[3];
floatArray[1] = new float[4];
floatArray[2] = new float[5];
二维数组初始化, 与一维数组初始化类似
int[][] num1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
二维数组初始化,每一行列数可以不相等
int[][] num2 = { { 78, 98 }, { 65, 75, 63, 63 }, { 98 } };
Last updated
Was this helpful?