作者qrtt1 (null)
站内java
标题Re: [问题] 字元阵列
时间Fri Apr 11 11:28:10 2008
※ 引述《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
1F:推 willieliao:LOL我没看equals的实作,thks a lot! 04/11 11:59
2F:推 tkcn:噢,我输了 XD 04/11 12:48