具有不同大小的多维数组 [英] Multidimensional arrays with different sizes

查看:69
本文介绍了具有不同大小的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是有一个想法可以测试一些东西,而且效果很好:

I just had an idea to test something out and it worked:

    String[][] arr = new String[4][4];

    arr[2] = new String[5];

    for(int i = 0; i < arr.length; i++)
    {
        System.out.println(arr[i].length);
    }

输出显然是:

4
4
5
4

所以我的问题是:

  • 这是好是坏的编码风格?
  • 这有什么好处?
  • 最重要的是,是否可以在声明本身中创建这样的构造?
  • 还...为什么甚至有可能这样做?

推荐答案

  • 这是好是坏的编码风格?
  • Is this good or bad style of coding?

与任何事物一样,这取决于情况.在某些情况下,锯齿状的数组(被称为)实际上是合适的.

Like anything, it depends on the situation. There are situations where jagged arrays (as they are called) are in fact appropriate.

  • 这有什么好处?
  • What could this be good for?

好,用于将不同长度的数据集存储在一个数组中.例如,如果我们有字符串"hello""goodbye",我们可能希望将它们的字符数组存储在一个结构中.这些char数组的长度不同,因此我们将使用锯齿数组.

Well, for storing data sets with different lengths in one array. For instance, if we had the strings "hello" and "goodbye", we might want to store their character arrays in one structure. These char arrays have different lengths, so we would use a jagged array.

  • 最重要的是,是否可以在声明本身中创建这样的构造?
  • And most of all, is there a way to create such a construct in the declaration itself?

是:

char[][] x = {{'h','e','l','l','o'},
              {'g','o','o','d','b','y','e'}};

  • 还...为什么甚至有可能这样做?
  • Also... why is it even possible to do?

因为Java语言规范§允许10.6 .

Because it is allowed by the Java Language Specification, §10.6.

这篇关于具有不同大小的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆