Re: [問題] 字元陣列
※ 引述《willieliao (Willie Liao)》之銘言:
: : 這裡有兩個 Java 的 development practice 可以一說.
: : 首先, 要習慣把 constant value 放在左邊, 即是要寫"".equals(xxx)
: : 因為 xxx 為變數, 有機會為 null, 寫成 "".equals(xxx)
: : 能正確 compare 避免 null pointer exception
: : 其次, compare empty string, 可能的話, 用 xxx.length() == 0
: : performance 應該會稍好一點點 (吧?) (這個有沒有人能證實一下? :P )
: 這個是真的,因為.length()是單純傳回String 物件內部那個char array的
: size,performance是O(1)
: "".equals(xxx)是比較hashcode,String這個class有overwrite hashcode()的實作
: 查api就知道hashcode是
: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
: 因此performance是 O(nlogn),length()大勝
: 恩,明天去把公司面試題庫加上這一題 ;p
Commons Lang 是這樣做的
因為即使不是null, 也有長度. 他也將全空白的考慮進去了 haha
========================================================================
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
========================================================================
另外 String 的 equals 有覆寫,
只會單純比較 ref 與 length 是不是相同再加以逐字母比對
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.133.80.216
推
04/11 11:59, , 1F
04/11 11:59, 1F
推
04/11 12:48, , 2F
04/11 12:48, 2F
討論串 (同標題文章)