java基础(数组)对象数组、引用数组、空洞判断
作者:互联网
//对象数组,引用数组
public class ArrayTest6 {
static class MyDate {
private int year;
private int month;
private int day;
public MyDate() {
}
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public String sya() {
return year + "年" + month + "月" + day + "日";
}
}
public static void main(String[] args) {
MyDate[] arr;//此时没有数组对象产生arr
arr = new MyDate[4];//创建了数组对象
//对象数组的元素,必须真的要把对象实体new出来
arr[0] = new MyDate(1875, 5, 5);
arr[1] = new MyDate(1905, 5, 10);
arr[2] = new MyDate(2005, 5, 15);
//下标为3的元素为null,极其危险,所以这样的元素称为空洞,因为不小心调用了对象的方法,就会出异常
for (int i = 0; i < arr.length; i++) {
//加入判断
if(arr[i]!=null){
System.out.println(arr[i].sya());//出现空指针异常,一定是有.操作
}else {
System.out.println(arr[i]);
}
}
}
}
标签:arr,java,int,MyDate,month,空洞,数组,year 来源: https://blog.csdn.net/asd623444055/article/details/122379919