当前位置 博文首页 > weixin_30374009的博客:Java数组(1):数组与多维数组

    weixin_30374009的博客:Java数组(1):数组与多维数组

    作者:[db:作者] 时间:2021-07-10 22:28

    我们对数组的基本看法是,你可以创建它们,通过使用整型索引值访问它们的元素,并且他们的尺寸不能改变。

    但是有时候我们需要评估,到底是使用数组还是更加灵活的工具。数组是一个简单的线性序列,这使得元素访问非常快速。但是为这种速度所付出的代价是数组大小被固定,并且在其生命周期中不可改变。

    无论使用哪种类型的数组,数组标识符只是一个引用。基本类型数组直接保存基本类型的值,对象数组保存一个指向其他对象的引用。

     1 class Apple {
     2     private static int count = 1;
     3 
     4     public Apple() {
     5         System.out.println("Apple" + count++);
     6     }
     7 }
     8 
     9 public class ArrayOptions {
    10     public static void main(String[] args) {
    11         Apple[] a; // 创建一个Apple类型的数组引用
    12         Apple[] b = new Apple[5]; // 创建一个Apple类型的数组对象,但是都指向null
    13         System.out.println("b: " + Arrays.toString(b)); // b: [null, null, null, null, null]
    14         Apple[] c = new Apple[4];
    15         for (int i = 0; i < c.length; i++)
    16             c[i] = new Apple(); // Apple1 Apple2 Apple3 Apple4
    17         // Aggregate initialization:
    18         Apple[] d = {new Apple(), new Apple(), new Apple()}; // Apple5 Apple6 Apple7
    19         // Dynamic aggregate initialization:
    20         a = new Apple[]{new Apple(), new Apple()}; // Apple8 Apple9
    21         System.out.println("a.length = " + a.length); // a.length = 2
    22         System.out.println("b.length = " + b.length); // b.length = 5
    23         System.out.println("c.length = " + c.length); // c.length = 4
    24         System.out.println("d.length = " + d.length); // d.length = 3
    25         a = d;
    26         System.out.println("a.length = " + a.length); // a.length = 3
    27 
    28         int[] e; // 创建一个基本类型的数组引用
    29         int[] f = new int[5]; // 创建一个Apple基本数组对象,初始化值都为0
    30         System.out.println("f: " + Arrays.toString(f)); // f: [0, 0, 0, 0, 0]
    31         int[] g = new int[4];
    32         for (int i = 0; i < g.length; i++)
    33             g[i] = i * i;
    34         int[] h = {11, 47, 93};
    35         System.out.println("f.length = " + f.length); // f.length = 5
    36         System.out.println("g.length = " + g.length); // g.length = 4
    37         System.out.println("h.length = " + h.length); // h.length = 3
    38         e = h;
    39         System.out.println("e.length = " + e.length); // e.length = 3
    40         e = new int[]{1, 2};
    41         System.out.println("e.length = " + e.length); // e.length = 2
    42     }
    43 }
    cs