加入收藏 | 设为首页 | 会员中心 | 我要投稿 4S站长网 (https://www.4s3.cn/)- 科技、混合云存储、数据迁移、云上网络、数据计算!
当前位置: 首页 > 编程开发 > Java > 正文

如果您在Java中显式初始化Object数组,那么包含与新的Object []不同?

发布时间:2020-11-17 05:54:38 所属栏目:Java 来源:互联网
导读:前言:这个问题已经被问到了 here,但是我特别想知道作者的具体含义. 我在Java中阅读Thinking,第3版.修订版4.0,Eckel在第4章初始化和清理中显示此代码段: public class ArrayInit{ public static void main(String[] args) { Integer[] a = { new Integer

前言:这个问题已经被问到了 here,但是我特别想知道作者的具体含义.

我在Java中阅读Thinking,第3版.修订版4.0,Eckel在第4章初始化和清理中显示此代码段:

public class ArrayInit
{
  public static void main(String[] args)
  {
    Integer[] a =
    {
      new Integer(1),new Integer(2),new Integer(3),};

    Integer[] b = new Integer[]
    {
      new Integer(1),};
  }
}

并声明如下:

The first form is useful at times,but it’s more limited since the size of the array is determined at compile time.
The second form provides a convenient syntax to create and call methods that can produce the same effect as C’s variable argument lists (known as “varargs” in C). These can include unknown quantities of arguments as well as unknown types.

我从来没有认识到这些与Eckel描述的不一样.据我了解,它们都是静态大小的数组.我不明白第一个比第二个更“限制”.

他在说什么?

解决方法

我认为这可能是作者所指的.

由于Java 5,我们可以使用可变参数列表声明函数.

public static int newStyleSum(final int... numbers) {
    int sum = 0;
    for (final int number : numbers) {
        sum += number;
    }
    return sum;
}

它们可以用于:

int s = newStyleSum(1,2,3,4);

这个功能只是语法糖.在内部,一个匿名数组被传递给该函数.

在我们有这个语法之前,上面的例子必须写成:

public static int oldStyleSum(final int[] numbers) {
    int sum = 0;
    for (int i = 0; i < numbers.length; ++i) {
        sum += numbers[i];
    }
    return sum;
}

并称为

int s = oldStyleSum(new int[]{1,4});  // "second" form

但不如

int s = oldStyleSum({1,4});  // "first" form (syntax error)

哪怕今天仍然是一个语法错误.

这可能是他正在谈论的. Java 5在2004年出版,所以对于2002年的书,这是有道理的.

新语法更灵活,更重要的是向后兼容,所以我们仍然可以做到

int s = newStyleSum(new int[]{1,4});

或者更重要的是,

int[] numbers = {1,4};
int s = newStyleSum(numbers);

如果我们想.

(编辑:4S站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读