2021.06.17——java数组

数组

概念
  • 同一种类型数据的集合。其实数组就是一个容器,一个特殊的对象。

  • 可以自动给数组中的元素从0开始编号,方便操作这些元素。

声明
  1. 第一种方法

    元素类型[] 数组名 = new 元素类型[元素个数或数组长度];

    int[] arr = new int[5];
  2. 第二种方法

    元素类型[] 数组名 = new 元素类型[]{元素,元素,……};

    int[] arr = new int[]{3,5,1,7};
遍历
int[] x = new int[]{ 1, 2, 3 };

for (int y = 0; y < x.length; y++) {

System.out.println(x[y]);

}
常见异常
  1. NullPointerException 空指针异常

    原因: 引用类型变量没有指向任何对象,而访问了对象的属性或者是调用了对象的方法

  2. ArrayIndexOutOfBoundsException 索引值越界。 原因:访问了不存在的索引值

posted @ 2021-06-17 16:59  叶不孤  阅读(34)  评论(0编辑  收藏  举报