一、一维数组的创建和使用
1.创建一维数组
1)先声明,再用new运算符进行内存分配
声明的方法有以下两种:
数组元素类型 数组名字[]
数组元素类型[] 数组名字
内存分配格式
数组名 = new 数组元素类型[数组元素的个数];
(2)声明的同时为数组分配内存
数组元素类型 数组名 = new 数组元素类型[数组元素个数]
(3)一维数组的初始化
有以下两种方式:
int arr[] = new int[]{1,2,3,5};
int arr2[] = {23,12,3,123,2}
2.使用一维数组
通过以下示例可以明白一维数组的使用:
public class TestArr1 {
public static void main(String args[]) {
int day[] = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
for(int i = 0;i<12;i++) {
System.out.println((i+1)+"月有"+day[i]+"天");
}
}
}
输出结果:
1月有31天
2月有28天
3月有31天
4月有30天
5月有31天
6月有30天
7月有31天
8月有31天
9月有30天
10月有31天
11月有30天
12月有31天
二、二维数组的创建和使用
1.创建二维数组
(1)先声明,再使用new运算符进行内存的分配
有一下两种:
数组元素类型 数组名字[][];
数组元素类型[][] 数组名字;
内存分配方法有一下两种:
1.直接为每一维分配内存空间
a = new int[2][4];
2.分别为每一维分配内存空间
a = new int[2][];
a[0] = new int[2];
a[1] = new int[4];
(2)声明的同时为数组分配内存
数组元素类型 数组名 = new 数组元素类型[元素个数][元素个数]
(3)二维数组的初始化
type arrayname[][] = {value1,value1.....};
2.使用二维数组
采用同样示例简要说明;
public class TestArr2{
public static void main(String args[]) {
int a[][] = new int[3][4];
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
System.out.println(a[i][j]);
}
System.out.println("-----------------------");
}
}
}
实验结果:
0
0
0
0
-----------------------
0
0
0
0
-----------------------
0
0
0
0
-----------------------
三、数组创建中使用new关键字的区别:
不同于String类,String由于实现了常量池 所以new 和不new 有区别:new的话,引用变量指向堆区。不new的话,引用变量指向常量池。
对于数组的定义,初始化时用new与不用new 没区别,只是两种方式罢了,因为数组是引用数据类型,建立对象时,无论用不用new,数组实体都是放在堆内存中,引用变量放在栈内存。