First off, let me start by saying that I don’t really like Java. We’re working from that assumption, understand? 🙂
Given the fact that I think Java is rediculously too verbose, I was happy to find a way to at least partially get the effect of PHP or Python array slices. Here it goes. Since the JDK 1.2, you can use the following code.
The senario is that we have one array, and we want to cut it into 2 halves. Theoretically, you could just copy the first half, or the second half, or any segment in the middle, so long as you have indexes to the array.
// Interpreted Java String myArray = new String[ 11 ]; // Get the sizes for the arrays. int firstHalfSize = myArray.length / 2; int secondHalfSize = myArray.length - firstHalfSize; String firstHalf = new String[ firstHalfSize ]; String secondHalf = new String[ secondHalfSize ]; // Arguments are: sourceArray, sourceStartIndex, destinationArray, destinationStartIndex, numElementsToCopy System.arraycopy( myArray, 0, firstHalf, 0, firstHalfSize ); System.arraycopy( myArray, firstHalfSize, secondHalf, 0, secondHalfSize );
The “System.arraycopy” method is very efficient; it’ll beat any loop you can write in your own code. (This is precisely why forward-thinking sripting languages like Python build this functionality into arrays from the start with a syntax like “myArray[ startIndex : length ]” (the colon is literal).)
So what does this mean? Use it. Bring happiness to those people who wind up using Java by speeding up an overly-verbose interpreted language.