Java 中的数组初始值设定项中带有尾随逗号的数组 [英] Arrays with trailing commas inside an array initializer in Java

查看:25
本文介绍了Java 中的数组初始值设定项中带有尾随逗号的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组初始化器可用于在编译时初始化数组.如下所示的带有尾随逗号的初始化程序可以正常编译.

Array initializers can be used to initialize arrays at compile-time. An initializer with trailing commas as shown below compiles fine.

int a[][] = {{1,2,} ,{3,4,} , {5,6,},}; //Trailing commas cause no compiler error

for(int i=0;i<a.length;i++)
{
    for(int j=0;j<2;j++)
    {
        System.out.print(a[i][j]+"\t");
    }
    System.out.println();
}

输出:

1        2        
3        4        
5        6     

<小时>

对于一维数组也是合法的,正如上面的讨论一样.


Also legal with one dimension arrays as obvious with the above discussion.

int[] b = {1, 2, 3, 4, 5, 6,}; //A trailing comma causes no compiler error

for(int i=0;i<b.length;i++)
{
    System.out.print(b[i]+"\t");
}

输出:

1        2        3        4        5        6

<小时>

即使以下是合法的语法并且编译良好.


Even the following is a legal syntax and compiles fine.

int c[][] = {{,} ,{,} , {,},}; 

编译器应该在逗号 , 之后和之前期望一个常量值(或另一个初始化器).这是怎么编译的?编译器是简单地忽略了这样的逗号还是在这种情况下会发生其他事情?

The compiler should expect a constant value (or another initializer) after and before a comma ,. How is this compiled? Does the compiler simply ignore such commas or something else happens in such a scenario?

推荐答案

尾随逗号被忽略.来自 Java 规范:

The trailing comma is ignored. From the Java specification:

数组初始值设定项中的最后一个表达式之后可能会出现尾随逗号并被忽略.

A trailing comma may appear after the last expression in an array initializer and is ignored.

这篇关于Java 中的数组初始值设定项中带有尾随逗号的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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