gpt4 book ai didi

java - Arrays.copyOfRange(byte[], int, int) 奇怪行为背后的逻辑是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:23:07 25 4
gpt4 key购买 nike

任何人都可以向我解释 Arrays.copyOfRange(byte[], int, int)) 的奇怪行为背后的逻辑吗? ?我可以用简单的例子来说明我的意思:

byte[] bytes = new byte[] {1, 1, 1};
Arrays.copyOfRange(bytes, 3, 4); // Returns single element (0) array
Arrays.copyOfRange(bytes, 4, 5); // Throws ArrayIndexOutOfBoundsException

在这两种情况下,我都将范围复制到数组边界之外(即 start >= array.length ),因此错误条件至少对我来说很奇怪(如果是 from < 0from > original.length )。在我看来应该是:if from < 0from >= original.length .也许我遗漏了什么?

最佳答案

The JavaDoc指定关于它期望的参数的三点:

一:

[from] must lie between zero and original.length, inclusive

两个:

[to] must be greater than or equal to from

三:

[to] may be greater than original.length

对于 Arrays.copyOfRange(bytes, 3, 4) 的情况,一、二和三为真,这意味着它们是有效的。

对于 Arrays.copyOfRange(bytes, 4, 5) 的情况,只有两个和三个为真,这意味着它们无效。


预期行为?是的。

不直观 行为?有点。

如果你的问题是 secret 的“为什么它是这样设计的?”那么除了代码作者,没有人能告诉你答案。

关于java - Arrays.copyOfRange(byte[], int, int) 奇怪行为背后的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46110986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com