Stavo attraversando un progetto open source, dove stavano creando un flusso di output, e mi sono imbattuto il seguente metodo:Lunghezza matrice Java inferiore a 0?
@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));
}
}
Così il byte[] buffer
è solo un normale vecchio byte[]
. Sappiamo che non è nullo. È anche possibile farlo avere una lunghezza inferiore a 0? Come, potrebbe essere fatto con riflessione e questo è quello che stanno di guardia contro?
Cosa intendi per "sappiamo che non è" null "? –
@EdwardThomson: Penso che la prima istruzione controlli 'buffer == null' –
Forse da qualche altra parte in quel progetto è una convenzione che' -1' è valido come un modo per dire che un indice non è valido o qualcosa del genere e qui finalmente si trasforma in un'eccezione. – thalador