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.
int[] a = new int[10];
{
int x = 10;
a[0] = x;
System.out.println(x);
}
System.out.println(x); // Error. x not visible here.
So, those braces just creates a local 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 minimize the scope of your local variables, which is absolutely a good idea, specially when, the variables created inside that block won't be used anywhere else.
So, if used without those braces, those variables will just hang around, waiting for the garbage collector to free them up, at the same time, enjoying the trip towards the end of current scope, that might be a very long method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With