我在使用concat時,並不清楚concat的實現原理。我就使用concat方法將兩個字符串拼接起來webImageRootPath.concat(path)。但是后來代碼報了java.lang.NullPointerException異常,檢查webImageRootPath並不異常為空,當時很納悶怎么會報空指針異常呢。從網上搜索之后發現,原來是path這個值為null。
-
public String concat(String str) {
-
int otherLen = str.length();
-
if (otherLen == 0) {
-
return this;
-
}
-
char buf[] = new char[count + otherLen];
-
getChars( 0, count, buf, 0);
-
str.getChars( 0, otherLen, buf, count);
-
return new String(0, count + otherLen, buf);
-
}
上面是concat的源碼實現。原來使用concat方法時,參數str也不能為null,否則就會包空指針異常。