数组由同一类型的对象或者基本数据组成,并封装在同一一个标识符(数组名称)下。
数组是对象
动态初始化
可以赋值给Object类型的变量
在数组中可以调用类Object的所有方法
二每个数组都有一 个由public final修饰的成员变量: length,即数组含有元素的个数( length可以是正数或零)
数组元素
注意:光理论是不够的,在此送大家一套2020最新Java架构实战教程+大厂面试题库,点击此处 进来获取 一起交流进步哦!
数组声明举例:
Type[] arrayName;
int[] intArray;
String[] stringArray;
Type arrayName[]
;int intArray[];
String stringArray[];
数组的创建举例:
int[] a;
a = new int [10];
String[] s;
s = new String[3]
int a[]=new int[1o];
String[] s1=new String[3], s2=new String[8];
int a[]={22, 33, 44, 55};
arrayName[index]
public class Arrays {
public static void main(String []args) {
int [] a1 = {1, 2, 3, 4, 5};
int [] a2 = a1;
for(int i=0; i<a2.length; i++)
a2[i]++;
for(int i=0; i<a1.length; i++)
System.out.println("a1[" + i + "] = " + a1[i]);
}
}
运行结果:
当运行int [] a2 = a1;
这一步时,并不是复制一个数组给a2,只是把引用a1赋值给引用a2。实际上a1,a2操作的是同一个数组。
System.arraycopy(src, srcPos, dest, destPos, length);
src
为被复制数组,srcPos
为被复制数组起始下标,dest
为复制数组,destPos
为复制数组下标,length
为想要复制的长度。以下代码用于复制copyFrom
从下标2开始的长度为7的数组。
public class ArraysCopy {
public static void main(String []args) {
char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j','k'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
类似一维数组,以二维数组为例:
int[][] a;
int[][] a = new int[3][3];
int[][] a ={{1,2,3},{4,5,6},{7,8,9}};
public class Arrays {
public static void main(String []args) {
int[][] Array = {{1, 2, 3}, {1, 2}, {8, 9, 10, 20, 50}};
System.out.println("Length of array is " + Array.length);
for(int i=0; i<3; i++)
System.out.println("Length of row[" + i +"] = " + Array[i].length);
}
}