Re: [問題] 字元陣列

看板java作者 (null)時間17年前 (2008/04/11 11:28), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串7/8 (看更多)
※ 引述《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
LOL我沒看equals的實作,thks a lot!
04/11 11:59, 1F

04/11 12:48, , 2F
噢,我輸了 XD
04/11 12:48, 2F
文章代碼(AID): #17_jhBJj (java)
文章代碼(AID): #17_jhBJj (java)