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

前端之家收集整理的这篇文章主要介绍了如果您在Java中显式初始化Object数组,那么包含与新的Object []不同?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
前言:这个问题已经被问到了 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);

如果我们想.

原文链接:https://www.f2er.com/java/125999.html

猜你在找的Java相关文章