JAVA零基础对象数组和对象数组的for-each循环

  • 对象数组
int[] arr = new int[10];
String[] a = new String[10];
System.out.println(arr[0]);
System.out.println(a[0]);

 


在两个数组中我们并没有给下标为0的两个数组进行赋值
运行结果:

 


 通过运行结果可以看出int类型的数组默认值为0,String类型的数组默认值为null


int[] arr = new int[10];
String[] a = new String[10];
System.out.println(arr[0]);
System.out.println(a[0].length());

 


如果我们想要计算null的长度可以通过.length函数进行计算

 

 运行结果报了个空指针异常,就说明null这个值是没有的,null表示空也就是没有的意思

对象数组中的每个元素都是对象的管理者而非对象本身

  • 象数组的for-each循环
class Value{
    private int i;

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }
}

 


我们编写一个类,成员变量有int i,并编写i的get和set方法
Value[] a = new Value[10];
for (int i = 0; i < a.length; i++) {
    a[i]=new Value();
    a[i].setI(i);
}
for (Value value : a) {
    System.out.println(value.getI());
    value.setI(0);
}
for (Value value : a) {
    System.out.println(value.getI());
}

 


在main方法中闯将Value类型的数组并利用for循环向数组中进行赋值操作,接着使用for-each循环遍历数组中的元素,
因为在赋值时已经将对象添加到了数组中,所以数组中的每一个值代表的都是一个对象,
所以在for-each循环遍历数组时需要调用.get函数将对象中的i获取并展示,接着我们再使用set方法将对象中i进行赋值,
所以我们再一次遍历时就都是已经赋值的那个值
posted @ 2022-06-22 11:05  ja不会va  阅读(337)  评论(0)    收藏  举报