问题
I have some source code that I need to make runnable under Java 5. Unfortunetly that code uses Arrays.copyOfRange function which was only introduced in Java 6. What would be the most effective way to implement same utility using only Java 5 API?
回答1:
Check out the OpenJDK 6 page - it's open source Java. You can download and read the source code yourself, find out how it's implemented, and add the functionality to the app manually.
回答2:
Here goes the code from OpenJDK for those who are intrested:
public static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
回答3:
The fastest way would be to use System.arraycopy
. It's what's done by the Arrays class, BTW.
来源:https://stackoverflow.com/questions/7970486/porting-arrays-copyofrange-from-java-6-to-java-5