Data structures 为什么;偏移量+;长度<;0“;在jdk中确保参数是否非法?
在jdk中,有许多地方可以检查array.eg附近的参数Data structures 为什么;偏移量+;长度<;0“;在jdk中确保参数是否非法?,data-structures,java,Data Structures,Java,在jdk中,有许多地方可以检查array.eg附近的参数 /*.......... * * @throws IllegalArgumentException * If <tt>offset</tt> is negative or greater than * <tt>buf.length</tt>, or if <tt>length</tt> is negative, or if *
/*..........
*
* @throws IllegalArgumentException
* If <tt>offset</tt> is negative or greater than
* <tt>buf.length</tt>, or if <tt>length</tt> is negative, or if
* the sum of these two values is negative.
*
* @param buf Input buffer (not copied)
* @param offset Offset of the first char to read
* @param length Number of chars to read
*/
public CharArrayReader(char buf[], int offset, int length) {
if ((offset < 0) || (offset > buf.length) || (length < 0) ||
//$ offset+length
(**(offset + length) < 0)**) {
throw new IllegalArgumentException();
}
this.buf = buf;
this.pos = offset;
this.count = Math.min(offset + length, buf.length);
this.markedPos = offset;
}
/*。。。。。。。。。。
*
*@galargumentException
*如果偏移量为负或大于
*buf.length,或者如果length为负数,或者如果
*这两个值之和为负值。
*
*@param buf输入缓冲区(未复制)
*@param offset要读取的第一个字符的偏移量
*@param-length要读取的字符数
*/
公共字符读取器(字符buf[],整数偏移量,整数长度){
如果((偏移量<0)| |(偏移量>基本长度)| |(长度<0)||
//$offset+长度
(**(偏移+长度)<0)***){
抛出新的IllegalArgumentException();
}
this.buf=buf;
this.pos=偏移量;
this.count=Math.min(偏移量+长度,单位长度);
this.markedPos=偏移量;
}
为什么Java
int
中的“(偏移量+长度)是有符号的,所以两个正的int
相加时可能会产生负值。它被称为环绕或我相信它是在检查溢出
整数的范围是-2147483648到2147483647
从代码中可以看到,有些地方需要偏移量+长度。如果偏移量+长度大于2147483647,就会出现问题,(偏移量+长度)<0)正在检查这种情况