尾随Java中的数组初始化内部逗号阵列 [英] Arrays with trailing commas inside an array initializer in Java

查看:118
本文介绍了尾随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:

一个结尾逗号可以在数组初始化的最后EX pression后出现,将被忽略。

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

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

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