java中数组操作常见的三个错误

数组操作常见3个问题

  1. 当访问但数组中不存在的角标时,ArrayIndexOutOfBoundsException

public class ArrayDemo2 {
    public static void main(String[] args) {
        int [] array = new int[3];
        //当访问但数组中不存在的角标时
        System.out.println(array[3]); //ArrayIndexOutOfBoundsException
    }
​
}
  1. 当引用型变量没有任何实体指向时,还在用其操作实体, NullPointerException

public class ArrayDemo2 {
    public static void main(String[] args) {
        int [] array = new int[3];
        //当引用型变量没有任何实体指向时,还在用其操作实体,就会发生该异常
        array = null;
        System.out.println(array[0]);//NullPointerException
    }
}
  1. [I@1b6d3586 @左边表示是一个int类型的数组,@右边是内存的hash值;

public class ArrayDemo2 {
    public static void main(String[] args) {
        int [] array = new int[3];
​
        System.out.println(array); //[I@1b6d3586 @左边表示是一个int类型的数组,@右边是内存的hash值;
    }
}
原文地址:https://www.cnblogs.com/benjieqiang/p/10594583.html