本文将介绍Java数组的创建与使用。
数组是相同类型数据的有序集合。 数组描述的是相同类型的若干个数据,按照一定的先后次序排列组合而成。其中,每一个数据称作一个数组元素,每个数组元素可以通过一个下标来访问他们
语法:
int[] arrayA = new int[3];
可以拆分为两个步骤:
int[] arrayA;
arrayC = new int[3];
语法:
int[] arrayB = new int[] {5,15,25};
可以拆分为两个步骤:
int[] arrayB;
arrayB = new int[] {5,15,25};
静态初始化时可以简化书写:
int[] arrayB = {5,15,25};
[0,length-1]
,如果越界就会报错。
ArraryIndexOutOfBoundsException
:数组下标越界异常!
适用于打印输出,不适合修改元素。
语法:
for(声明语句 : 表达式){
//代码句子
}
示例:
public class demo {
public static void main(String[] args) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x + "\n");
}
}
}
输出结果:
10
20
30
40
50
数组可以作为参数传递给方法。
示例:求和传入数组(整形)的和
public class demo {
public static void sum(int[] array) {
int s = 0;
for (int i = 0; i < array.length; i++) {
s = s + array[i];
}
System.out.println(s); //10
}
public static void main(String[] args) {
sum(new int[]{1,2,3,4});
}
}
输出结果:
10
示例:实现数组翻转
public class demo {
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;
}
public static void main(String[] args) {
int[] result = reverse(new int[]{1,2,3,4});
for(int x : result){
System.out.println(x);
}
}
}
输出结果:
4
3
2
1
示例:
int[][] arrays = new int[2][2];public class demo {
public static void main(String[] args) {
int[][] arrays = new int[2][2]; //创建二维数组
arrays[0][0] = 1;
System.out.println(arrays[0][0]); //1
}
}
输出结果:
1
参考:《Java数组详解》