Porting Arrays.copyOfRange from Java 6 to Java 5

2019-08-01 06:22发布

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?

3条回答
Ridiculous、
2楼-- · 2019-08-01 06:40

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.

查看更多
等我变得足够好
3楼-- · 2019-08-01 06:43

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;
}
查看更多
Summer. ? 凉城
4楼-- · 2019-08-01 06:59

The fastest way would be to use System.arraycopy. It's what's done by the Arrays class, BTW.

查看更多
登录 后发表回答