java作為目前最受開發人員歡迎以及熱度最高的一門語言,在很多方面展現出了其特性,雖然靈活性不比c++,執行效率不比c,開發效率不比Ruby,但是作為最早最純粹的OO語言,java在目前來說因為其在編程方面有著與c及c++語言的延續性而被廣泛的使用。即使java是如此的受歡迎,個人覺得jdk的api在很多方面卻做的不是太好,簡單的以命名來說。比如說string類的兩個方法replace和replaceAll,因為有replaceAll的存在根據命名來看很容易使人覺得第一個replace方法是用replacement字串替換source字串中第一個出現的target字串,而replaceAll方法是替換在source字串中所出現的所有target字串。
至少在jdk中它們是這樣聲明的:public String replaceAll(String regex, String replacement) {...}
public String replace(CharSequence target, CharSequence replacement){...}
如果不去閱讀它們的注釋或者查看具體實現,你自然的覺得它們二者就只是存在著替換數量之間的差別,一個是全部替換,另外一個只是替換第一個(至少我是這樣理解的,並且在此api上面也吃過一些虧)。二者的注釋分別為:replaceAll Replaces each substring of this string that matches the given
regular expression with the given replacement.replaceReplaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".到此才得知replaceAll是採用Regex進行文本的替換,替換所有滿足條件的substring。replace是採用文本本身的內容進行匹配替換,也是所有滿足條件的substring。
例如下面的代碼:
String info = "catfish+foolishcat";String withReplace = info.replace("catfish+", "rxr");String withReplaceAll = info.replaceAll("catfish+", "rxr");System.out.println("withReplace is " + withReplace);System.out.println("withReplaceAll is " + withReplaceAll);
最後的輸出分別為:
withReplace is rxrfoolishcat
withReplaceAll is rxr+foolishcat所以這兩個方法在命名上面給開發人員的歧義性太大,不具備可讀性,至少不能望文生義,replace替換成replaceWithLiteralTarget,replaceAll替換成replaceWithRegexTarget能夠從語義上面區分出二者的差別。針對replace和replaceAll命名的就說這麼多,有時間把個人認為jdk中不好的一些define都拿出來記錄一下,以免以後犯同樣的錯誤。