This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
This is a routine that is called alot to clear a buffer used to load a file. Could someone tell me how to clear a char array without clearing it one element at a time. Cheers
See the "Arrays" class. Look for the "fill" method. Of course, it will clear each array element. I'll usually do something like track how many I want to use in the array so I don't have to worry about clearing the array.
Java does not have any memory manipulation operators like C's memset which would allow the array to be cleared in one operation (well, almost none). Instead, if you really have to clear the array, you have to clear each element individually (which is what the "Arrays" method does). For some VMs, keeping a reference emptied array of the same size and using System.arraycopy() might be faster. Theoretically, a VM can implement System.arraycopy() as a memcpy command, and even generate that in native-code to make the copy as fast as possible. In practice System.arraycopy() usually seems to be impemented as a simple loop. But Paul's second answer is dead on. Why bother to clear the array. Just fill it with the new chunk, but keep a record of how much has been filled and don't operate on elements past the top filled index. Many of the Java collection objects use exactly this mode of operation - see the Vector class implementation for example. This is faster than the fastest possible memory clearing method you could have, because you avoid the operation completely.