--- tags: Java --- # 文字處理  ## String 1. JDK1.0 1. 記憶體 * a.不用new: 常數pool, 若資料相同可直接使用, 不會產生新物件。經常使用這個方式。 * b.文字組合: 有兩個方式01.concat():只能使用在String. 02. 加號(+):可以使用在任何資 料。 關於'+' 運算元至少一個是String(跳脫運算子使用規則),必會產生新物件。 * c.改變時產生新物件: 使用String method ## StringBuffer * StringBuffer其實就是一種String,用法幾乎和String一樣,但提供更多方法去操作字串,利用char[]的特性來做操作,以減少記憶體浪費。 * 所提供的字串鏈結方法append(),會在記憶體後面增加空間,而不是在建立一個記憶體區塊,大大提升效率。 ## StringBuilder * 跟StringBuffer一樣都是mutable。 * 是non-tread-safe的。 ## 資料比較 ### `==` * Primitive * 實質是否相等: 比較物件(實體、記憶體空間)是否相同。 ### Object.equals() * Reference: 內容物是否相同,比較兩個物件的記憶體參照位置。 * 參考類型的物件,equals()跟==是一樣的功能,但String、Integer...等等的類,有覆寫equals的功能,比對的結果會跟自定義的類別有所不同。 > 何時需要Override equals()? > 當你需要比較物件的邏輯相等(非物件一致性)時,且預設的equals( )無法滿足你的需求時,就需要override equals( )。 > 引用至[https://medium.com/joe-tsai/equals-hashcode-4480f4580be4] 範例 ``` Ball s1 = new Ball("Luke", "ball", "red"); Ball s2 = new Ball("Luke", "ball", "red"); String s3= "rest" + "ful" ; String s4 = new String("restful") ; String s5 = new String("restful") ; String s6 = new String("peaceful") ; String s7 = s4 ; String s8= "restful" ; String s9= "restful" ; System.out.println(s1.equals(s2)) ; //false System.out.println(s4.equals(s5)) ; //true System.out.println(s4.equals(s8)) ; //true System.out.println(s5.equals(s6)) ; //false System.out.println(s4 == s5) ; //false System.out.println(s4 == s7) ; //true System.out.println(s4 == s8) ; //false System.out.println(s8 == s9) ; //true System.out.println(s3 == s8) ; //true ``` new String比較特別,在equals比較時,內容值相同就會是true,其他物件都會是false。  ### hashCode() 跟equals() 的比較 * 跟equals一樣比較對象是否一致 * 覆寫equals方法裡面都會比較複雜,會使效率不好,而使用hashCode()去比較,只要生成一個hash值就可,效率會高很多。 * 既然hashCode()效率比較好,那為何還要equals()呢?因為hashCode()並不是完全可靠,有時候不同的物件他們生成的hashcode也會一樣 * equals()相等的兩個物件他們的hashCode()肯定相等,也就是用equals()比較是最正確的。 * hashCode()值相等,並不代表equals()出來的結果會相等,只單看hashCode()值,並不一定準確。 > [name=Luke] [time=Sun, Jan 12, 2020] [color=#907bf7]
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up