Can anybody explain the following codes to me? It is from the Android source code.
The first line looks to me is to initialize an integer array, but what about those codes enclosed in braces? I mean are those codes syntax correct since the braces part
seems to be tangling?
// 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;
}
}
Yeah those code blocks are absolutely fine. They are viable syntax. Rather they are useful.
What happens there is, the code is just shifted to an unnamed-block, to provide them a block scope. So, any variables defined inside that block won’t be visible outside.
So, those
bracesjust creates alocal block scope, that’s it. Nothing more special in them. Though, you won’t feel the magic of those blocks in the above code.This way of coding is generally used to
minimizethe scope of yourlocal variables, which is absolutely a good idea, specially when, thevariablescreated inside that block won’t be used anywhere else.So, if used without those
braces, those variables will justhangaround, waiting for thegarbage collectorto free them up, at the same time, enjoying thetriptowards the end ofcurrent scope, that might be a very longmethod.