这可能是一个奇怪的问题,但却是一个有效的问题。 我知道下面的语句没有编译错误:
ArrayList list = new ArrayList();;; //(with three `;` semi-colon)好的,现在我写了下面的import语句:
import java.util.ArrayList;;; (with three `;` semi-colon)但是我得到了以下编译错误:
Syntax error on token ";", invalid StaticImportOnDemandDeclarationName为什么?
This might be a weird question, but a valid one. I know below statement does not have compilation error:
ArrayList list = new ArrayList();;; //(with three `;` semi-colon)Okay now I have written below import statement:
import java.util.ArrayList;;; (with three `;` semi-colon)But I got below compilation error:
Syntax error on token ";", invalid StaticImportOnDemandDeclarationNameWhy?
最满意答案
你有什么:
ArrayList list = new ArrayList();;; //(with three `;` semi-colon)不是以三个分号结束的声明。 这是一个由一个分号结束的声明,后面是两个空的声明 。
空语句在Java中是合法的,但Java源文件的导入部分不包含语句,它由导入声明组成。
JLS 14.6定义了空语句:
空语句什么都不做。
EmptyStatement: ;执行空语句总是正常完成。
可能合法使用空语句:
//loop forever while (true) {;} // the body of this loop is an empty statement.换句话说,在第一个示例中,您有一个赋值后跟两个空语句。 分号不是严格多余的。
import部分有自己的语法,没有一个语法规则允许任意的分号。 语法由JLS 7.5指定:
ImportDeclaration: SingleTypeImportDeclaration TypeImportOnDemandDeclaration SingleStaticImportDeclaration StaticImportOnDemandDeclaration SingleTypeImportDeclaration: import TypeName ; ...What you have here:
ArrayList list = new ArrayList();;; //(with three `;` semi-colon)is not a statement terminated with three semi-colons. It's a statement terminated by one semi-colon, followed by two empty statements.
An empty statement is legal in Java, but the import section of a Java source file is not comprised of statements, it's comprised of import declarations.
JLS 14.6 defines the Empty Statement:
An empty statement does nothing.
EmptyStatement: ;Execution of an empty statement always completes normally.
A perhaps-legitimate use of the empty statement:
//loop forever while (true) {;} // the body of this loop is an empty statement.In other words, in your first example, you have an assignment followed by two empty statements. The semicolons are not strictly superfluous.
The import section has its own grammar, and none of the grammar rules allow for an arbitrary semi-colon. The grammar is specified by JLS 7.5:
ImportDeclaration: SingleTypeImportDeclaration TypeImportOnDemandDeclaration SingleStaticImportDeclaration StaticImportOnDemandDeclaration SingleTypeImportDeclaration: import TypeName ; ...更多推荐
发布评论