文章目录
前言
最近阅读了下JDK17中的InputStream源码,在读到其中readNBytes(int len)方法时,有一段代码让我产生了一些疑惑。所以便分析了下代码。理解的不对的话,希望各位大佬予以答疑解惑。
一、问题是什么?
我认为如下代码中 while 循环可以直接使用 if 语句替代。while循环不仅多了一次判断过程,而且相对来说if语句更容易理解。
jdk中源码如下:
public byte[] readNBytes(int len) throws IOException {
if (len < 0) {
throw new IllegalArgumentException("len < 0");
}
List<byte[]> bufs = null;
byte[] result = null;
int total = 0;
int remaining = len;
int n;
do {
byte[] buf = new byte[Math.min(remaining, DEFAULT_BUFFER_SIZE)];
int nread = 0;
//=================就是这里while换成if效果应该是一样的=================
// read to EOF which may read more or less than buffer size