• java数组


                                               一维数组

         数组说的通俗一点就是把许多数据类型相同的数据放在一起

    在Java中,可以使用以下格式来定义一个数组。如下

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

    int[] x = new int[100];

    上述语句就相当于在内存中定义了100个int类型的变量,第一个变量的名称为x[0],第二个变量的名称为x[1],以此类推,第100个变量的名称为x[99],这些变量的初始值都是0。为了更好地理解数组的这种定义方式,可以将上面的一句代码分成两句来写,具体如下:

    int[] x;           // 声明一个int[]类型的变量

    x = new int[100]; // 创建一个长度为100的数组

                                                       数组的遍历

    public class ArrayDemo04 {

    public static void main(String[] args) {

    int[] arr = { 1, 2, 3, 4, 5 }; // 定义数组

    // 使用for循环遍历数组的元素

    for (int i = 0; i < arr.length; i++) {

    System.out.println(arr[i]); // 通过索引访问元素

    }

    }

    }

    首先定义一个数组arr,接着定义一个for循环,其中i就相当于是指针的作用,用来指向数组里面的数据

                                                             

                                                                   数组越界异常

    每个数组的索引都有一个范围,即0~length-1。在访问数组的元素时,索引不能超出这个范围,否则程序会报错,如下所示。

     1 public class ArrayDemo06 {

    public static void main(String[] args) {

    int[] arr = new int[4]; // 定义一个长度为4的数组

    4  System.out.println("arr[0]=" + arr[4]); // 通过4访问数组元素

    5  }

    6 }

    运行结果如下图所示。

     

     这就是数组越界了,数组中只有4个元素,下标为1到3,找不到下标为4的元素

                                                           空指针异常

    在使用变量引用一个数组时,变量必须指向一个有效的数组对象,如果该变量的值为null,则意味着没有指向任何数组,此时通过该变量访问数组的元素会出现空指针异常,接下来通过一个案例来演示这种异常,

     1 public class ArrayDemo07 {

    public static void main(String[] args) {

    int[] arr = new int[3]; // 定义一个长度为3的数组

    4  arr[0] = 5; // 为数组的第一个元素赋值

    5  System.out.println("arr[0]=" + arr[0]); // 访问数组的元素

    6  arr = null; // 将变量arr置为null

    7  System.out.println("arr[0]=" + arr[0]); // 访问数组的元素

    8  }

    9 }

     以为在第六行将arr的值设置为null所以找不到,程序报错

    好了,以为数组暂时先将这么多,等明天再写二维数组和多维数组

  • 相关阅读:
    Digital Video Stabilization and Rolling Shutter Correction using Gyroscope 论文笔记
    Distortion-Free Wide-Angle Portraits on Camera Phones 论文笔记
    Panorama Stitching on Mobile
    Natural Image Stitching with the Global Similarity Prior 论文笔记 (三)
    Natural Image Stitching with the Global Similarity Prior 论文笔记(二)
    Natural Image Stitching with the Global Similarity Prior 论文笔记(一)
    ADCensus Stereo Matching 笔记
    Efficient Large-Scale Stereo Matching论文解析
    Setting up caffe on Ubuntu
    Kubernetes配置Secret访问Harbor私有镜像仓库
  • 原文地址:https://www.cnblogs.com/jingyukeng/p/8626054.html
Copyright © 2020-2023  润新知