简体   繁体   English

Java数组长度小于0?

[英]Java array length less than 0?

I was going through an open source project where they were creating an output stream, and came across the following method: 我正在经历一个他们正在创建输出流的开源项目,并遇到了以下方法:

@Override public void write(byte[] buffer, int offset, int length) {
    if (buffer == null) {
        throw new NullPointerException("buffer is null");
    }
    if (buffer.length < 0) { // NOTE HERE
        throw new IllegalArgumentException("buffer length < 0");
    }
    if (offset < 0) {
        throw new IndexOutOfBoundsException(String.format("offset %d < 0", offset));
    }
    if (length < 0) {
        throw new IndexOutOfBoundsException(String.format("length %d < 0", length));
    }
    if (offset > buffer.length || length > buffer.length - offset) {
        throw new IndexOutOfBoundsException(String.format("offset %d + length %d > buffer"                                                       " length %d", offset, length, buffer.length));
    }
}

So the byte[] buffer is just a normal old byte[] . 所以byte[] buffer只是一个普通的旧byte[] We know it's not null. 我们知道它不是空的。 Is it even possible to make it have a length of less than 0? 它甚至可以使它的长度小于0吗? Like, could it be done with reflection and that's what they're guarding against? 比如,它可以通过反思完成,这就是他们正在防范的事情吗?

No, this can never happen. 不,这永远不会发生。 The length is guaranteed to be non-negative as per the Java specifications. 根据Java规范,长度保证是非负的。

The members of an array type are all of the following: 数组类型的成员是以下所有成员:

  • The public final field length, which contains the number of components of the array. public final字段长度,包含数组的组件数。 length may be positive or zero . 长度可以是正数或零

Source: JLS §10.7 资料来源: JLS§10.7

As mprivat mentioned, if you ever try to create an array of negative size, a NegativeArraySizeException will be thrown. 正如mprivat所提到的,如果您尝试创建负数大小的数组,则会抛出NegativeArraySizeException

I don't believe it's possible. 我不相信这是可能的。 Even through reflection, it is guarded with NegativeArraySizeException 即使通过反射,它也会受到NegativeArraySizeException的保护

This is just an exception handling issue. 这只是一个异常处理问题。 You're allowed to create an array with a negative size in Java - it wont even throw an exception when you compile it. 您可以在Java中创建一个负数大小的数组 - 它在编译时甚至不会抛出异常。 But at run time, your program won't run until this is corrected. 但在运行时,您的程序将不会运行,直到更正。 (It will throw a NegativeArraySizeException .) (它会抛出NegativeArraySizeException 。)

The problem is with this exception being thrown at run time instead of compile time - That's why the exception has been handled with IllegalArgumentException . 问题是在运行时而不是编译时抛出此异常 - 这就是使用IllegalArgumentException处理异常的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM