Tuesday, 15 March 2011

Post 5 - Populating arrays (again)...

Quick post of a discovery. Yet again I want to create a (comparatively) small array, and initialize it to contain 'false'. In a previous post I discovered the way to do this is:

Boolean[] mask = new Boolean[maskSize];
for (int j = 0; j < maskSize; j++) {
     mask[j] = false;
}

In my travels across the interwebs I have also discovered another way to fill it, which looks a bit neater:

Boolean[] mask = new Boolean[maskSize];
Arrays.fill(mask, false);

I do enjoy cutting down for loops to single lines. However, digging a bit deeper, Arrays.fill() simply uses a for loop inside it, so usually runs in the same time. Worse though, (at least in eclipse) when Arrays is first called, presumably it must load the class, which puts another overhead, increasing the runtime by quite a lot! I suspect if you were to compile it to a .jar file and run it, either way would be equivalent, but seeing as I'll mostly be using this in eclipse I might as well leave it as a for loop!

As an aside, some of my posts here are actually quite embarassing, but I figure if I don't post embarassing stuff, I'll never learn! Not to mention this blog would be a lot shorter too!

No comments:

Post a Comment