一维数组
1.1数组的定义
1.1.1声明数组
声明一个数组引用对象
elementType [] arrayName;
elementType arrayName [];
- 数组声明不能指定数组元素个数
- 数组是引用数据类型,也就是说数组是一个对象,数组名即为引用名。数组声明时实际上是声明一个引用变量。如果数组元素为引用类型,则该数组为对象数组,可以继承objet类的所有方法。
1.1.2创建数组
为每个元素分配存储空间
arrayName=new elementType[arraySize];
- 数组的大小可以在运行过程中指定(c➕➕不行)
默认值
- 数值型 0
- 字符型‘\u0000'
- 布尔型false
- 数组元素是引用类型null
1.1.3访问数组
arrayName[index];
访问数组元素
arrayName.length
1.1.4数组初始化器
double[] marks = new double[]{10,20,30};
1.2增强的for
double sum=0;
for(double score:mark)
{
sum=sum+score;
}
System.out.println("sum="+sum);
1.3.数组的复制
int[] source={10,20,30};
int[] target=new int[source.length];
for(int i=0;i<3;i++)
{
target[i]=source[i];
}
int[] source={10,20,30};
int[] target=new int[source.length];
System.arraycopy(source,0,target,0,3);
1.4 数组参数与返回值
数组可以作为方法的参数和返回值
参数
public static int sumArray(double array[]){
double sum=0;
for(int i=0;i<=array.length;i++){
sum=sum+array[i];
}
return sum;
}
数组作为引用参数,如果在方法内修改数组元素的值,则该修改反映到返回的数组
2.Array类
2.1数组的排序
public static void sort(int[] a)//对数组a按自然顺序排序
public static void sort(int[] a,int fromIndex,int toIndex)//对数组a按起始下标fromIndex到终止下标toIndex排序
public static void sort(object[] a)//对数组a按自然顺序排序
public static void sort(object[] a,int fromIndex,int toIndex)//对数组a按起始下标fromIndex到终止下标toIndex排序
- 不能对布尔型数组排序
2.2数组元素的查找
public static void binarySearch(int []a,int key)
public static void binarySearch(object []a,int key)
- 使用binarySearch()方法之前,数组必须已经排序好了
2.3数组元素的复制
public static boolean[] copyOf(boolean[] original,int newLength);
public static double[] copyOf(double[] original,int newLength);
public static <T>[] copyOf(T[] original,int newLength);
public static boolean[] copyOf(boolean[] original,int from,int to);
public static double[] copyOf(double[] original,int from,int to);
public static <T>[] copyOf(T[] original,int from,int to);
2.4填充数组元素
public static void fill(int []a,int val):用指定的val值填充a中的每个元素
public static void fill(int[] a,int fromIndex,int toIndex,int val):用指定的val值填充数组a起始下标fromIndex到终止下标toIndex的每一个元素
public static void fill(Object []a,int val):用指定的val值填充a中的每个元素
public static void fill(Object[] a,int fromIndex,int toIndex,int val):用指定的val值填充数组a起始下标fromIndex到终止下标toIndex的每一个元素
2.5数组的比较
public static boolean equals(boolean[] a,boolean[] b);
public static boolean equals(Object[] a,Object[] b);
3.二维数组
3.1二维数组的声明
elementType [] [] arrayName;
elementType [] arrayName[];
elementType arrayName[] [] ;
3.2创建二维数组
1.直接分配
适用于第二维数组元素数量相同
int [][] matrix = new int [2][3];
2,先分配一维,再分配二维
在java中二维数组是数组的数组
int [][] matrix = new int [2][];
matrix[0]=new int[3];
matrix[1]=new int[3];
3.3数组初始化器
int [][] matrix = {(10,20,30),
(40,50,60),
(70,80,90),};
Java支持多维数组!