将 Arrays.copyOfRange 从 Java 6 移植到 Java 5

发布于 2024-12-12 20:31:26 字数 251 浏览 3 评论 0原文

我有一些源代码需要在 Java 5 下运行。不幸的是,该代码使用 Arrays.copyOfRange 函数,仅在 Java 6 中引入。仅使用 Java 5 API 实现相同实用程序的最有效方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

捂风挽笑 2024-12-19 20:31:26

以下是来自 OpenJDK 的代码,供感兴趣的人参考:

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;
}

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;
}
千纸鹤 2024-12-19 20:31:26

查看 OpenJDK 6 页面 - 它是开源 Java。您可以自行下载并阅读源代码,了解其实现方式,并手动将功能添加到应用程序中。

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.

佼人 2024-12-19 20:31:26

最快的方法是使用 System.arraycopy。顺便说一句,这就是 Arrays 类所做的事情。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文