这个 Android Java 代码中的语法是什么意思?

3
有人能给我解释一下以下代码吗?这段代码来自Android源代码
第一行看起来是初始化一个整数数组,但是花括号中的代码怎么样呢?我的意思是,这些代码的语法是否正确,因为花括号部分似乎有点混乱?
    // high priority first
    mPriorityList = new int[mNetworksDefined];
    {
        int insertionPoint = mNetworksDefined-1;
        int currentLowest = 0;
        int nextLowest = 0;
        while (insertionPoint > -1) {
            for (NetworkAttributes na : mNetAttributes) {
                if (na == null) continue;
                if (na.mPriority < currentLowest) continue;
                if (na.mPriority > currentLowest) {
                    if (na.mPriority < nextLowest || nextLowest == 0) {
                        nextLowest = na.mPriority;
                    }
                    continue;
                }
                mPriorityList[insertionPoint--] = na.mType;
            }
            currentLowest = nextLowest;
            nextLowest = 0;
        }
    }

你是指第三行的 { 吗?它完全没问题,那是一个代码块。可以把它看作是 if(true) { ... } 的简写形式。 - ignis
第3行的外部块表示在}关闭后,变量insertionPointcurrentLowestnextLowest不再使用。带有new[]的块可以放置在单独的初始化方法中。 - Joop Eggen
1个回答

2

是的,这些代码块是完全正常的。它们是可行的语法。相反,它们是有用的。

发生的情况是,代码只是转移到一个未命名的块中,以为它们提供块范围。因此,在该块内定义的任何变量在外部都不可见。

int[] a = new int[10];
{
    int x = 10;
    a[0] = x;
    System.out.println(x);
}

System.out.println(x);  // Error. x not visible here.

因此,那些大括号只是创建了一个局部代码块作用域,仅此而已。除此之外没有什么特别的。虽然,在上面的代码中你不会感受到这些代码块的神奇之处。
通常使用这种编码方式来将局部变量的范围最小化,这绝对是一个好主意,特别是当在该块内创建的变量不会在其他地方使用时。
因此,如果没有那些大括号使用,那些变量将会“挂在那里”,等待垃圾收集器释放它们,同时享受旅程并且可能要一直等到当前范围结束,而这可能是一个非常长的方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接