为什么有数组呢?
数组是用于储存多个相同类型数据的集合。如果我们需要存储很多个相同类型的数据就需要用到数组。
数组有哪些特点?
1,数组是一种引用类型。
2,数组当中的数据的数据类型必须统一。
3,数组在程序运行过程中不能改变长度。
基本数据类型和引用类型的区别可以参考这几篇文章
1,基本数据类型:https://www.cnblogs.com/ppzhang/p/15604490.html
2,引用类型:https://www.cnblogs.com/SilentCode/p/4858790.html
数组如何初始化?
一种是动态初始化,一种是静态初始化
动态初始化的格式: 数据类型[ ] 数组名称 = new 数据类型[ 100 ];
//不拆分的形式
int[] arrayA = new int[100];
//拆分的形式
int[] arrayA;
arrayA = new int[100];
**静态初始化格式:**数据类型[ ] 数组名称 = new 数组类型[ ] { 数据1 , 数据2, …};
//不拆分的形式
int[] arrayB = new int[]{2,5,9};
//拆分形式
int[] arrayB;
arrayB = new int[]{2,5,9};
//省略的形式
int[] arrayB = {2,5,9};
动态初始化的数组为什么有值?
数据类型 | 默认初始值 |
---|---|
int | 0 |
double或者float | 0.0 |
char | ‘\u0000’ |
boolean | false |
引用类型如String | null |
如何遍历数组?
使用数组名称.length可以很方便地实现遍历数组
public static void main(String[] args) {
//先创建一个数组arrayList
int[] arrayList = new int[]{1,3,6,8};
//遍历数组并打印
for (int i = 0; i <arrayList.length ; i++) {
System.out.println(arrayList[i]);
}
}
常见的错误?
ArrayIndexOutOfBoundsException
这是因为数组索引越界导致的错误,改正方法就是将索引数值改为数组长度-1。
public static void main(String[] args) {
int[] arrayList = new int[]{1,3,6,8};
for (int i = 0; i <4; i++) {
System.out.println(arrayList[i]);
}
}
/*错误提示
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
因为数组长度是4而且索引值是从0开始不是从1开始,所以数组的索引值最大是3。
只需要将for (int i = 0; i <4; i++) 改为for (int i = 0; i <3; i++) 即可。
*/
public static void main(String[] args) {
int[] arrayList = new int[]{1,3,6,8};
for (int i = 0; i <3; i++) {
System.out.println(arrayList[i]);
}
}
NullPointerException
空指针是因为没有对数组初始化。
public static void main(String[] args) {
int[] arrayList = null;
for (int i = 0; i <arrayList.length ; i++) {
System.out.println(arrayList[i]);
}
}
/*错误提示
Exception in thread "main" java.lang.NullPointerException
因为只声明了arrayList,而没有对其初始化。
只需要将int[] arrayList = null;改为
int[] arrayList = null;
arrayList = new int[100];
即可
*/
public static void main(String[] args) {
int[] arrayList = null;
arrayList = new int[100];
for (int i = 0; i <arrayList.length ; i++) {
System.out.println(arrayList[i]);
}
}