zoukankan      html  css  js  c++  java
  • Java Array数组使用详解

    本文主要讲解java中array数组使用,包含堆、栈内存分配及区别

    1.动态初始化

    package myArray;
    /*
    * 堆:存储的是new出来的东西,实体,对象
    * A 每个对象都有地址值
    * B 每个对象的数据都有默认值
    *      byte,short,int,long 0
    *      float,double 0.0
    *      char 'u0000'
    *      boolean false
    *      引用类型 null
    *  C 使用完毕会在垃圾回收站空闲时被回收
    *

    * 动态初始化:
    * 数据类型[] 数组名 = new 数据类型[数组长度];

    
    * */
    public class ArrayTest {
        public static void main(String[] args) {
            int[] arr = new int[3];//指定数组长度
            System.out.println(arr[0]);
            System.out.println(arr[1]);
            System.out.println(arr[2]);
            System.out.println("------------");
    
            arr[0] = 100;
            System.out.println(arr[0]);
            System.out.println(arr[1]);
            System.out.println(arr[2]);
        }
    }

    打印结果

    2.静态初始化

    package myArray;
    /*
     * 静态初始化的格式:
     *         数据类型[] 数组名 = new 数据类型[]{元素1,元素2,元素3,...};
     *
     *         举例:
     *             int[] arr = new int[]{1,2,3};
     *
     *         简化格式:
     *             数据类型[] 数组名 = {元素1,元素2,元素3,...};
     *             int[] arr = {1,2,3};
     */
    public class ArrayJingTaiChuShiHua {
        public static void main(String[] args) {
            int[] arr = {1,2,3,4};
            System.out.println(arr[3]);
        }
    }

    结果如下

    java中内存分配图

    一些名词解释

    数组:存储同一种数据类型的多个元素的容器。
    数组初始化:
             A:所谓的初始化,就是为数组开辟内存空间,并为数组中的每个元素赋予初始值
             B:我们有两种方式可以实现数组的初始化
                 a:动态初始化    只给出长度,由系统给出初始化值
                 b:静态初始化    给出初始化值,由系统决定长度
    //输出数组名
    // System.out.println("arr:"+arr); //[I@104c575
    //我们获取数组的地址值是没有意义的,我要的是数组中的元素值,该怎么办呢?
    //不用担心,Java已经帮你想好了这个问题
    //其实数组中的每个元素都是有编号的,编号从0开始,最大的编号是n-1
    //通过数组名和编号的配合使用我们就可以获取指定编号的元素值
    //这个编号的专业叫法:索引
    //访问格式:数组名[索引]


  • 相关阅读:
    Hadoop 启动脚本分析与实战经验
    mac appium-Andriod sdk安装
    windows解决appium-doctor报gst-launch-1.0.exe and/or gst-inspect-1.0.exe cannot be found
    windows解决appium-doctor报opencv4nodejs cannot be found
    windows解决appium-doctor报 mjpeg-consumer cannot be found.
    windows解决appium-doctor报ffmpeg cannot be found问题
    windows解决appium-doctor报 bundletool.jar cannot be found
    内存分配和垃圾回收调优
    内存分配与回收策略
    JVM老年代和新生代的比例
  • 原文地址:https://www.cnblogs.com/longesang/p/10819748.html
Copyright © 2011-2022 走看看